Socket编程

≯℡__Kan透↙ 提交于 2019-12-05 15:23:15

以下只是进行了一次的收发例子。

客户端和服务器端是两个解决方案。

服务器端
static void main(string[] args){
//1.创建Socket对象
Socket tcpServer=new Socket(AddressFamily.InterNetworl,SocketType.Stream,ProtocolType.Tcp);
 //2.绑定IP和端口号(软件的端口号唯一)
IPAddress ipaddress=new IPAddress(new byte[]{192,168,0,112});
EndPoint point=new IPEndPoint(ipaddress,7788);
tcpServer.Bind(point);//向操作系统申请一个可用的ip和端口号用来做通信
//3.开始监听(等待客户端连接)
tcpServer.Listen(100);//最大连接数
Socket clientSocket=tcpServer.Accept();//暂停当前线程,直到有一个客户端连接过来,之后进行下面的代码
//使用返回的Socke跟客户端做通信
string message="hello 欢迎你";
byte[] data=Encodeing.UTF8.GetBytes(message);//对字符串做编码,得到一个字符串的字节数组
clientSocket.Send(data):
byte[]data2= new byte[1024];//创建一个字节数组接收客户端发过来的数据
int length=clientSocket.Receive(data2);
string message2=Encoding.UTF8.GetString(data2,0,length);
Console.WriteLine(message2);
}

客户端
static void main(string[] args){
//1.创建Socket对象
Socket tcpClient=new Socket(AddressFamily.InterNetworl,SocketType.Stream,ProtocolType.Tcp);
//2.发起建立连接的请求
IPAddress ipaddress=IPAddress.Parse("192.168.0.112")//可以把一个字符串的ip地址转换成一个ipaddress的对象
EndPoint point=new IPEndPoint(ipaddress,7788);//端口号保持一致
tcpClient.Connect();//通过IP和端口号来定位一个要连接到的服务器端
byte[] data = new byte[1024];
int length=tcpClient.Receive(data);//这里传递一个byte数组,实际上这个data数组用来接收数据
//Length表示返回值接收了多少字节的数据
string message=Encoding.UTF8.GetString(data,0,length);//只把接收到的数据做个转化
Console.WriteLine(message);
//向服务器端发送消息
string message2=Console.ReadLine();//读取用户的输入,把输入的信息发送到服务器端
tcpClient.Send(Encoding.UTF8.GetBytes(message2));//把字符串变为字节。
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!