其他分享
首页 > 其他分享> > scoket通信(基础)

scoket通信(基础)

作者:互联网

服务端

 1 namespace t1_Scoket
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             //1、创建socket对象
 8             Socket socket = new Socket(
 9                     AddressFamily.InterNetwork,//采用IPv4协议
10                     SocketType.Stream,//数据传输方式,一般采用流式传输
11                     ProtocolType.Tcp//采用TCP协议方式传输
12                                     );
13 
14             //2、绑定/连接:指定IP与Port  用Bind() 
15             socket.Bind(new IPEndPoint(IPAddress.Parse("本机IPv4号"),10030));
16 
17             //3、开始监听Listen()
18             socket.Listen(10);
19 
20             Console.WriteLine("服务器启动");
21             //4、接受客户端请求Accept,可以获取到客户端对象
22              Socket sClient=  socket.Accept();
23             //Accept()等待客户端连接,同时会阻塞当前线程
24             //Receive()等待接受客户端发送信息,若客户端没用发送信息,Receive()方法也会阻塞当前线程
25             Console.WriteLine("接受到客户端的请求");
26 
27             //5、接受客户端报文Receive 
28             byte[] bs = new byte[1024];
29            int len= sClient.Receive(bs);
30             Console.WriteLine("客户端的请求,如下:");
31 
32             //处理正文,向客户端发送报文Send
33             string s2 = Encoding.UTF8.GetString(bs, 0, len);
34             Console.WriteLine(s2);
35             s2 += "hs";
36             sClient.Send(Encoding.UTF8.GetBytes(s2));
37             Console.ReadLine();
38         }
39     }
40 }

客户端

 1 namespace t1_Client
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             //1、创建scoket对象
 8             Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
 9 
10             //2、连接:指定IP、Port
11             client.Connect(IPAddress.Parse("本机IPv4号"), 10030);
12 
13             byte[] bs = new byte[1024];
14             //3、发送信息
15             string s1 = Console.ReadLine();
16             if (s1=="1")
17             {
18                 bs = Encoding.UTF8.GetBytes("小胡来了");
19                 client.Send(bs);
20             }
21 
22             //接受响应,进行处理
23             int len = client.Receive(bs);
24             Console.Write(Encoding.UTF8.GetString(bs, 0, len));
25             while (client.Available>0)
26             {
27                 len = client.Receive(bs);
28                 Console.WriteLine(Encoding.UTF8.GetString(bs,0,len));
29             }
30 
31             Console.WriteLine("123");
32             Console.ReadKey();
33         }
34     }
35 }

 

标签:Console,scoket,Receive,基础,通信,len,WriteLine,bs,客户端
来源: https://www.cnblogs.com/hs1637-smy/p/15631175.html