哇,这真是一个巨大的主题。如果你在学习之前没有学习过网络套接字。我可以给你要点,但绝对不够。
客户端:
public void Get()
{
string data;
string input;
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Connect(ipep);
}
catch (SocketException e)
{
Console.WriteLine("Unable to connect to server");
Console.WriteLine(e.ToString());
return;
}
NetworkStream ns = new NetworkStream(socket);
StreamWriter sw = new StreamWriter(ns);
StreamReader sr = new StreamReader(ns);
data = sr.ReadLine();
Console.WriteLine(data);
while (true)
{
input = Console.ReadLine();
if (input == "exite")
break;
sw.WriteLine(input);
sw.Flush();
data = sr.ReadLine();
Console.WriteLine(data);
}
Console.WriteLine("Disconnected from server...");
socket.Close();
ns.Close();
sr.Close();
sr.Close();
}
服务器:
public void Get()
{
string data;
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ipep);
socket.Listen(10);
Console.WriteLine("Waiting for a client...");
Socket client = socket.Accept();
IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with: {0}, at Port: {1}", newclient.Address, newclient.Port);
NetworkStream ns = new NetworkStream(client);
StreamReader sr = new StreamReader(ns);
StreamWriter sw = new StreamWriter(ns);
string welcome = "Welcome to my test server";
sw.Write(welcome);
sw.Flush();
while (true)
{
try
{
data = sr.ReadLine();
}
catch (IOException)
{
break;
}
Console.WriteLine(data);
sw.WriteLine(data);
sw.Flush();
}
Console.WriteLine("Disconnected from {0}", newclient.Address);
sw.Close();
ns.Close();
sr.Close();
}
请在控制台应用程序上试用,看看它是如何工作的。
基本上,服务器打开端口(本例中为 9050)等待客户端连接,然后客户端连接到服务器,然后开始通信。
你提到你必须使用 UDP 套接字,我想你知道 udp,但如果不是,你最好检查一下 TCP 和 UDP 之间的区别,特别是关于验证数据是否到达所需目的地的方式(临时概念等上)。