TcpListener和TcpClient类是对Socket的进一步封装,为基于TCP协议的网络通信提供更加便捷的调用方式。
TcpListener在服务器负责监听和接受客户端的连接请求,TcpClient类提供一系列可用于TCP网络通信的API,是以流的方式来读写数据的,调用GetStream的方法会发挥一个NetworkStream实例,即可发送和接收数据。
C#的TcpListener类与TcpClient类使得网络编程更加方便。
接下来简单介绍一下服务器与客户端通信的示例。
TcpListener实例化
private const int LOCAL_PORT = 8688;
TcpListener listener = null;
listener=new TcpListener(IPAddress.Any,LOCAL_PORT);
listener.Start();
txtRecMsgs.AppendText("正在监听:" + IPAddress.Any + ":" + LOCAL_PORT.ToString()+"\n");
listener.BeginAcceptTcpClient(new AsyncCallback(acceptCallback), listener);
调用BeginAcceptTcpClient方法将异步接受连接,当有新的连接传入时,会触发AsyncCallback委托绑定的方法。
private void acceptCallback(IAsyncResult ar)
{
TcpListener lstn = (TcpListener)ar.AsyncState;
TcpClient client = lstn.EndAcceptTcpClient(ar);
Task.Run(() =>
{
string host = client.Client.RemoteEndPoint.ToString();
NetworkStream stream = client.GetStream();
while (true)
{
byte[] buffer = new byte[4];
stream.Read(buffer, 0, 4);
int len = BitConverter.ToInt32(buffer, 0);
buffer = new byte[len];
stream.Read(buffer, 0, len);
string recMsg = Encoding.UTF8.GetString(buffer);
if (recMsg == "$END$")
{
string message = "客户端" + host + "发送了退出指令\n";
txtRecMsgs.Invoke(new Action(() => txtRecMsgs.AppendText(message)));
break;
}
else
{
txtRecMsgs.Invoke((Action)delegate ()
{
string message = string.Format("来自{0}的消息:{1}\n", host, recMsg);
txtRecMsgs.AppendText(message);
});
}
}
client.Close();
});
lstn.BeginAcceptTcpClient(new AsyncCallback(acceptCallback), lstn);
}
客户端
TcpClient实例化
TcpClient client = null;
client = new TcpClient(txtIP.Text.Trim(), Convert.ToInt32(txtPort.Text));
private void SendMessage()
{
string msg = textBox3.Text;
if (client == null) return;
if (client.Connected == false) return;
byte[] data = Encoding.UTF8.GetBytes(msg);
int len = data.Length;
byte[] buffer = BitConverter.GetBytes(len);
client.GetStream().Write(buffer, 0, 4);
client.GetStream().Write(data, 0, data.Length);
}
注意:进行两台机器之间的通信的话,输入服务器的Ip以及服务器监听的端口即可
源代码:http://download.csdn.net/detail/kevin_iot/9750884
参考资料
C# 6.0学习笔记