今天学习了c#网络编程的一些东西,在这里记下来。
1、客户端连接远程服务器
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("192.168.0.123"), 8500);
2、服务端打开端口等待客户端连接
IPAddress ip = new IPAddress(new byte[] { 192, 168, 0, 123 });
TcpListener listener = new TcpListener(ip, 8500);
listener.Start();
Console.WriteLine("Start Listenning ...");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
}
3、发送消息
byte[] temp = Encoding.Unicode.GetBytes(msg);
NetworkStream streamToServer.Write(temp, 0, temp.Length);
同步接收消息
int byteRead = streamToClient.Read(buffer, 0, 8192);
string msg = Encoding.Unicode.GetString(buffer, 0, byteRead);
异步接收消息
AsyncCallback callBack = new AsyncCallback(ReadComplete);
streamToServer.BeginRead(buffer, 0, BufferSize, callBack, null);
ReadComplete(IAsyncResult ar)是回调函数,当异步接收执行完成以后,会自动调用回调函数。
private void ReadComplete(IAsyncResult ar)
{
int bytesRead;
try
{
lock (streamToServer)
{
bytesRead = streamToServer.EndRead(ar);
}
if (bytesRead == 0)
{
throw new Exception("读取到0字节");
}
string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received: {0}",msg);
Array.Clear(buffer, 0, buffer.Length);
lock (streamToServer)
{
AsyncCallback callBack = new AsyncCallback(ReadComplete);
streamToServer.BeginRead(buffer, 0, BufferSize, callBack, null);
}
}
catch(Exception ex)
{
if (streamToServer != null)
{
streamToServer.Dispose();
client.Close();
Console.WriteLine(ex.Message);
return;
}
}
}