Tcp编写流程

来源:互联网 发布:赵阳网络竞价 编辑:程序博客网 时间:2024/05/31 19:24

一.服务器端

1.声明一个套接字

Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

2.声明并绑定一个IP和端口,建立连接

IPAddress ipaddress = new IPAddress(new byte[] { 192, 168, 1, 122 });
EndPoint point = new IPEndPoint(ipaddress, 7788);
 //向操作系统申请一个可用的通信地址用来做通信
 tcpServer.Bind(point);

3.开始监听客户端,

tcpServer.Listen(100);

4.等待用户输入信息并发送过来

Socket clientSocket = tcpServer.Accept();

5.对用户输入的进行相应的操作(通过转码向客户端发送消息)

string message = "hello 服务器欢迎你";
byte[] data = Encoding.UTF8.GetBytes(message);
clientSocket.Send(data);


二.客户端

1.声明一个套接字

Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

2.声明一个端口和IP

IPAddress ipaddress = IPAddress.Parse("192.168.0.101");
            EndPoint point = new IPEndPoint(ipaddress, 23278);
            

3.与服务器建立连接

tcpClient.Connect(point);

4.向服务器发送数据或接受服务器的数据

byte[] data = new byte[1024];
            int length = tcpClient.Receive(data);
            string message = Encoding.UTF8.GetString(data, 0, length);
            Console.WriteLine(message);

1.1.


原创粉丝点击