C# Socket编程

释放双眼,带上耳机,听听看~!

闲着无聊,写了个简单的C/S Socket程序,功能很简单,服务器在9000端口监听socket接入,只要有接入,就发送"Welcome."消息给客户端。

代码分2块,server端:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
1class Program
2    {
3        static void Main(string[] args)
4        {
5            TcpListener lsner = new TcpListener(9000);
6            lsner.Start();
7            Console.WriteLine("started in port: 9000");
8            while (true)
9            {
10                TcpClient client=lsner.AcceptTcpClient();
11                Console.WriteLine("new client received. hashcode: {0}", client.GetHashCode());
12                ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessTcpClient), client);
13            }
14            Console.ReadKey();
15        }
16
17        private static void ProcessTcpClient(object state)
18        {
19            TcpClient client=state as TcpClient;
20            if(client==null)
21                Console.WriteLine("client is null");
22
23            NetworkStream ns=client.GetStream();
24            StreamWriter sw = new StreamWriter(ns);
25            sw.WriteLine("Welcome.");
26            sw.Flush();
27            sw.Close();
28            client.Close();
29        }
30

 

client端:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
1class Program
2    {
3        static void Main(string[] args)
4        {
5            IPAddress address = IPAddress.Parse("127.0.0.1");
6            IPEndPoint ep=new IPEndPoint(address, 9000);
7            TcpClient client = new TcpClient();
8            client.Connect(ep);
9            NetworkStream ns=client.GetStream();
10            StreamReader sr = new StreamReader(ns);
11            Console.WriteLine(sr.ReadToEnd());
12            sr.Close();
13            sr.Dispose();
14            ns.Close();
15            ns.Dispose();
16            client.Close();
17            Console.ReadKey();
18        }
19    }
20

 

运行效果图如下:

 C# Socket编程

 

给TA打赏
共{{data.count}}人
人已打赏
安全技术

Bootstrap 4 Flex(弹性)布局

2021-12-21 16:36:11

安全技术

从零搭建自己的SpringBoot后台框架(二十三)

2022-1-12 12:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索