C#Socket_TCP,客户端,服务器端通信

客户端与服务器通信,通过IP(识别主机)+端口号(识别应用程序)。

IP地址查询方式:Windows+R键,输入cmd,输入ipconfig。

端口号:可自行设定,但通常为4位。

服务器端:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading.Tasks;

namespace _021_socket编程_TCP协议

{

class Program

{

static void Main(string[] args)

{

Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //TCP协议

//IP+端口号:ip指明与哪个计算机通信,端口号(一般为4位)指明是哪个应用程序

IPAddress ipaddress = new IPAddress(new byte[] { 192, 168, 43, 231 });

EndPoint point = new IPEndPoint(ipaddress, 7788);

tcpServer.Bind(point);

tcpServer.Listen(100);

Console.WriteLine("开始监听");

Socket clientSocket = tcpServer.Accept();//暂停当前线程,直到有一个客户端连接过来,之后进行下面的代码

Console.WriteLine("一个客户端连接过来了");

string message1 = "hello 欢迎你";

byte[] data1 = Encoding.UTF8.GetBytes(message1);

clientSocket.Send(data1);

Console.WriteLine("向客户端发送了一条数据");

byte[] data2 = new byte[1024];//创建一个字节数组做容器,去承接客户端发送过来的数据

int length = clientSocket.Receive(data2);

string message2 = Encoding.UTF8.GetString(data2, 0, length);//把字节数据转化成 一个字符串

Console.WriteLine("接收到了一个从客户端发送过来的消息:" + message2);

Console.ReadKey();

}

}

}

客户端:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading.Tasks;

namespace _001_socket编程_tcp协议_客户端

{

class Program

{

static void Main(string[] args)

{

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

IPAddress ipaddress = IPAddress.Parse("192.168.43.231");

EndPoint point = new IPEndPoint(ipaddress, 7788);

tcpClient.Connect(point);

byte[] data = new byte[1024];

int length = tcpClient.Receive(data);

string message = Encoding.UTF8.GetString(data, 0, length);

Console.WriteLine(message);

//向服务器端发送消息

string message2 = Console.ReadLine();//客户端输入数据

tcpClient.Send(Encoding.UTF8.GetBytes(message2));//把字符串转化成字节数组,然后发送到服务器端

Console.ReadKey();

}

}

}

注意:要实现客户端与服务器端通信,应分别为其建立工程,并且应该先运行服务器。