1.socket编程-tcp服务器端
创建Socket
将Socket绑定ip跟端口号。IPEndPoint是对ip+端口做了封装
用IPAddress存储ip
使用Socket类中Bind来进行绑定,Listen方法设定最大连接数。
Accept方法暂停当前线程,直到有一个客户端链接过来,再往下进行。
接收到客户端消息,向客户端发送一个消息。socket只能传送Byte类型的数据。
class Program
{
static void Main(string[] args)
{
//1.创建socket
Socket tcpServer = new Socket
(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//2.绑定ip跟端口号
IPAddress ipaddress = new IPAddress(new byte[]{192,168,1,103});
EndPoint point = new IPEndPoint(ipaddress,7788);//ipendpoint是对ip+端口做了一层封装的类
tcpServer.Bind(point);//向操作系统申请一个可用的port和ip用来做通信
//3.监听(等待客户端连接)
tcpServer.Listen(100);//参数是最大连接数
//4.暂停当前线程,直到有一个客户端链接过来,之后进行下面的代码.使用返回的Socket跟客户端做通信
Socket clientSocket = tcpServer.Accept();
string message = "hello 欢迎你";
byte[] data = Encoding.UTF8.GetBytes(message);
clientSocket.Send(data);
}
}
2.tcp客户端
创建Socket
通过ip和port定位一个要连接的服务器
定义byte 将接收到的数据存储再data中
将接收到的数据转换成string
class Program
{
static void Main(string[] args)
{
//1.socket creat
Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//2.发起建立连接的请求
IPAddress ipaddress = IPAddress.Parse("192.168.1.103");
EndPoint point = new IPEndPoint(ipaddress,7788);
tcpClient.Connect(point);//通过IP和Port定位一个要连接道德服务器端
//3.接受服务器端发过来的消息
byte[] data = new byte[1024];
int length = tcpClient.Receive(data);//length表示接受了多少字节的数据
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine(message);
Console.ReadKey();
}
}
3.客户端发送消息给服务器
客户端
string message2 = Console.ReadLine();
tcpClient.Send(Encoding.UTF8.GetBytes(message2));
服务器端
byte[] data2 = new byte[1024];//存储客户端发送过来的数据
int length = clientSocket.Receive(data2);
string message2 = Encoding.UTF8.GetString(data2, 0,length);
Console.WriteLine("接收到客户端发送的消息" + message2);