一个简单的TCP客户端、服务端会话程序(C#)

服务端:
1. new 一个TcpListener listner
2.listner.start
3.while(true)
4. 获取socket :Socket s = listner.AcceptSocket();
5. 获取netstream:NetworkStream ns = new NetworkStream(s);
6.读取netstream: StreamReader sr = new StreamReader(ns);
  string command = sr.ReadLine();
7.应答: byte[] res = Encoding.UTF8.GetBytes("回答内容");
         s.Send(res);


客户端
1. new TcpClient client
2. 获取流 :  NetworkStream stream = client.client.GetStream();
            StreamReader reader = new StreamReader(stream);
3. 请求内容:byte[] cmd = Encoding.UTF8.GetBytes("请求内容");
4.发送请求:stream.Write(cmd, 0, cmd.Length);
5.获取回应(商定为空的时候退出):while (true)
            {
                result = reader.ReadLine();
                if (result.Equals(""))
                    break;
                Console.WriteLine(result);
            }
6.关闭连接:client.Close();

你可能感兴趣的:(一个简单的TCP客户端、服务端会话程序(C#))