如何向服务器发送多个“消息”? System.Net.Sockets.SocketException

时间:2019-03-28 20:27:20

标签: c# python-3.x winforms sockets visual-studio-2017

我正在尝试在c#中设置基本客户端以与python服务器通信。它能够向服务器发送一个“消息”,但是在第二次尝试时抛出System.Net.Sockets.SocketException。

完整错误:

  

System.IO.IOException:无法从传输读取数据   连接:已建立的连接被软件中止   您的主机。在System.Net.Sockets.Socket.Receive(Byte []   缓冲区,Int32偏移量,Int32大小,SocketFlags(SocketFlags)位于   System.Net.Sockets.NetworkStream.Read(Byte []缓冲区,Int32偏移量,   Int32大小)

我的C#代码:

//This creates a button that sends text entered in 'textbox2' to the server when clicked
private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                NetworkStream serverStream = clientSocket.GetStream();
                byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$");
                serverStream.Write(outStream, 0, outStream.Length);
                serverStream.Flush();

                byte[] inStream = new byte[4096];
                aDataStream.Text = outStream.ToString();

//The line below is where the error occurs, it works the first time but fails the second time I click the button.
                int bytesRead = serverStream.Read(inStream, 0, inStream.Length);

                string returndata = System.Text.Encoding.ASCII.GetString(inStream, 0, bytesRead);
                msg(returndata);
                textBox2.Text = "";
                textBox2.Focus();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
            }

        }

这是python中的服务器代码:

import socketserver


class MyTCPHandler(socketserver.BaseRequestHandler):

    def handle(self):
        print("Client Connected")
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "127.0.0.1", 5000

    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)

    server.serve_forever()

0 个答案:

没有答案
相关问题