服务器端:(tcp协议)
1.创建socket
Socket tcpServer=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
2.绑定ip跟端口号 ip找到计算机 端口号找到软件 范围0-60000
IPAddress ipaddress=new IPAddress(new byte[]{10,28,120,164}); //ip地址 在搜索器上cmd,然后搜ipconfig查找ip地址
EndPoint point=new IPEndPoint(ipaddress,7788); ipendpoint是对ip+端口做了一层封装的类
tcpServer.Bind(point); 向操作系统申请一个可用的ip和端口号 用来通信
3.开始监听(等待客户端做连接)
tcpServer.Listen(100); 参数是最大连接数
Console.WriteLine("开始监听");
4.接收连接
Socket clientSocket= tcpServer.Accept(); 暂停当前线程,直到有一个客户端连接过来,之后进行下面的代码
Console.WriteLine("一个客户端连接过来了")
使用返回的socket跟客户端做通信
5.发送消息
string message="hello 欢迎你";
byte[] date = Encoding.UTF8.GetBytes(message); 对字符串做编码,得到一个字符串的字节数组
clientSocket.Send(date);
Console.WriteLine("向客户端发送了一条数据")
byte[] date2=new byte[1024]; 创建一个字节数组用来当做容器,去承接客户端发送过来的数据
int length=clientSocket.Receive(date2);
string message2=Encoding.UTF8.GetString(date2,0,length); 把字节数据转化成一个字符串
Console.WriteLine("接收到了一个从客户端发送过来的消息"+message2)
Console.ReadKey();
客户端:(tcp协议) (另外一个项目做)
1.创建一个Socket
Socket tcpClient = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
2.发起建立连接的请求
IPAddress ipaddress=IPAddress.Parse("10,28,120,164") 可以把一个字符串的ip地址转化成一个ipaddress的对象
EndPoint point=new IPEndPoint(ipaddress,7788); 保持一致
tcpClient.Connect(point); 通过ip+端口号定位一个要连接到的服务器端
3接收消息
byte[] date=new byte[1024];
int length=tcpClient.Receive(date) 这里传递一个byte数组,实际上这个date数组用来接收数据
length返回值表示接收了多少字节的数据
string message=Encoding.UTF8.GetString(date,0,length); 从0号开始到length长度,只把接收的数据做一个转化
Console.WriteLine(message);
//向服务器端发送消息
string message2=Console.ReadLine(); 读取用户的输入,把输入发送到服务器端
tcpClient.Send(Encoding.UTF8.GetBytes(message2)); 把字符串转化为字节数组,然后发送到服务器端
Console.ReadKey();