关于服务器端与客户端的交互



关于服务器端与客户端的交互
首先,服务器端与客户端的交互涉及到两个方面,一个服务器,一个客户端。下面将进行的一个列子是,客户端发送信息给服务器端,服务器端根据客户发送的请求再返回信息给客户端。
服务器端:
定义变量

        private TcpListener tcpListener; //监听
        private Thread listenThread;//线程
        private int connectedClients = 0;//连接数
        private delegate void WriteMessageDelegate(string msg);//发送返回信息的委托

开始监听,并启动监听的线程

  private void Server()
        {
            this.tcpListener = new TcpListener(IPAddress.Loopback, 3000); // Change to IPAddress.Any for internet wide Communication
            this.listenThread = new Thread(new ThreadStart(ListenForClients));
            this.listenThread.Start();
        }
        private void ListenForClients()
        {
            this.tcpListener.Start();

            while (true) // Never ends until the Server is closed.
            {
                //blocks until a client has connected to the server
                TcpClient client = this.tcpListener.AcceptTcpClient();

                //create a thread to handle communication 
                //with connected client
                connectedClients++; // Increment the number of clients that have communicated with us.
                lblNumberOfConnections.Text = connectedClients.ToString();

                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                clientThread.Start(client);
            }
        }


在开启的线程中,调用” HandleClientComm “这个方法来接受客户端发来的请求,其中传递的变量client是一个连接着服务器端的通信。从这个通信里面获取客户端发来的消息。

private void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();

            byte[] message = new byte[4096];
            int bytesRead;

            while (true)
            {
                bytesRead = 0;

                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch
                {
                    //a socket error has occured
                    break;
                }

                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    connectedClients--;
                    lblNumberOfConnections.Text = connectedClients.ToString();
                    break;
                }

                //message has successfully been received
                ASCIIEncoding encoder = new ASCIIEncoding();

                // Convert the Bytes received to a string and display it on the Server Screen
                string msg = encoder.GetString(message, 0, bytesRead);
                WriteMessage(msg);

                // Now Echo the message back

                //Echo(msg, encoder, clientStream);
            }

            tcpClient.Close();
        }

在” HandleClientComm”这个方法中,使用” WriteMessage “返回对客户端的请求
        private void WriteMessage(string msg)
        {
            if (this.rtbServer.InvokeRequired)
            {
                WriteMessageDelegate d = new WriteMessageDelegate(WriteMessage);
                this.rtbServer.Invoke(d, new object[] { msg });
            }
            else
            {
                this.rtbServer.AppendText(msg + Environment.NewLine);
            }
        }


服务器端结束后,我们来看下客户端是如何发送请求,并且如何接受服务器端的请求。
客户端
初始化变量

   private string myMessage = ""; //发送的信息
   private TcpClient client = new TcpClient();//通信
   private IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);//链接的IP

在页面加载时,就连接服务器端

  public Form1()
        {
            InitializeComponent();
            client.Connect(serverEndPoint);            
        }

打开连接后,服务器端输入要发送的信息,并对信息发送,和对服务器端信息的接受

 private void RtbClientKeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData != Keys.Enter || e.KeyData != Keys.Return)
            {
                myMessage += (char)e.KeyValue;
            }
            else
            {
                
                SendMessage(myMessage);
                
                myMessage = "";
            
            }
        }

        private void SendMessage(string msg)
        {
            NetworkStream clientStream = client.GetStream();

            ASCIIEncoding encoder = new ASCIIEncoding();
            byte[] buffer = encoder.GetBytes(msg);

            clientStream.Write(buffer, 0, buffer.Length);
            clientStream.Flush();

            // Receive the TcpServer.response.

            // Buffer to store the response bytes.
            Byte[]  data = new Byte[256];

            // String to store the response ASCII representation.
            String responseData = String.Empty;

            // Read the first batch of the TcpServer response bytes.
            Int32 bytes = clientStream.Read(data, 0, data.Length);
            responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
            
            rtbClient.AppendText(Environment.NewLine + "From Server: " + responseData);
        }

在上段代码中,负责发送的代码是

            NetworkStream clientStream = client.GetStream();

            ASCIIEncoding encoder = new ASCIIEncoding();
            byte[] buffer = encoder.GetBytes(msg);

            clientStream.Write(buffer, 0, buffer.Length);
            clientStream.Flush();

负责接受的代码是

    // Receive the TcpServer.response.

            // Buffer to store the response bytes.
            Byte[]  data = new Byte[256];

            // String to store the response ASCII representation.
            String responseData = String.Empty;

            // Read the first batch of the TcpServer response bytes.
            Int32 bytes = clientStream.Read(data, 0, data.Length);
            responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
            
            rtbClient.AppendText(Environment.NewLine + "From Server: " + responseData);

关于此处的client.GetStream 可以参照下面的链接
# TcpClient.GetStream Method
http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.getstream(v=vs.110).aspx
完整的代码,可以参照如下的链接下载:
# TCP / IP Server Client Example Part 1
https://code.msdn.microsoft.com/windowsapps/TCP-IP-Server-Client-0964d476


_______________________________________________________________________________________________________________________

欢迎大神光临菜鸟博客,希望能得到各位大神在编码方面的指引,同时欢迎与我一样刚进入编程世界的朋友一起讨论学习!相信前进的道路上,有你们,编程世界会更加精彩!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值