c#使用TCP协议实现数据发送和接受
使用TCP协议实现数据的发送和接受包括客户端和服务端两个部分;
1. 服务端代码如下所示:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;class Program
{static void Main(){// 设置服务器IP地址和端口号IPAddress ip = IPAddress.Parse("127.0.0.1");//写入实际的IP地址int port = 8888;// 创建TCP监听器TcpListener listener = new TcpListener(ip, port);listener.Start();Console.WriteLine("等待客户端连接...");// 接受客户端连接TcpClient client = listener.AcceptTcpClient();Console.WriteLine("客户端已连接");// 获取网络流NetworkStream stream = client.GetStream();// 读取客户端发送的数据byte[] buffer = new byte[1024];int bytesRead = stream.Read(buffer, 0, buffer.Length);string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);Console.WriteLine("接收到数据: " + dataReceived);// 向客户端发送数据string dataToSend = "Hello, Client!";byte[] dataBytes = Encoding.ASCII.GetBytes(dataToSend);stream.Write(dataBytes, 0, dataBytes.Length);Console.WriteLine("已发送数据: " + dataToSend);// 关闭连接stream.Close();client.Close();listener.Stop();}
}
2. 客户端代码:
using System;
using System.Net.Sockets;
using System.Text;class Program
{static void Main(){// 设置服务器IP地址和端口号string serverIP = "127.0.0.1";int serverPort = 8888;// 创建TCP客户端TcpClient client = new TcpClient();client.Connect(serverIP, serverPort);Console.WriteLine("已连接到服务器");// 获取网络流NetworkStream stream = client.GetStream();// 向服务器发送数据string dataToSend = "Hello, Server!";byte[] dataBytes = Encoding.ASCII.GetBytes(dataToSend);stream.Write(dataBytes, 0, dataBytes.Length);Console.WriteLine("已发送数据: " + dataToSend);// 读取服务器发送的数据byte[] buffer = new byte[1024];int bytesRead = stream.Read(buffer, 0, buffer.Length);string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);Console.WriteLine("接收到数据: " + dataReceived);// 关闭连接stream.Close();client.Close();}
}
总结:上述示例使用服务器端创建一个TCP监听器,等待客户端连接。当客户端连接后,服务器端从客户端接收数据,并向客户端发送数据。客户端则连接到服务器,向服务器发送数据,并接收服务器发送的数据。