如果客户端断开连接,Python TCP服务器将关闭

时间:2020-04-17 23:24:35

标签: python c# tcp

这是我的TCP服务器的代码 PYTHON:

import socket
from cookieLED import callLED

host = ''
port = 5459

storedValue = "Hello!"

def setupServer():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("Socket created.")
    try:
        s.bind((host, port))
    except socket.error as msg:
        print(msg)
    print("Socket bind comlete.")
    return s

def setupConnection():
    s.listen(1) # Allows one connection at a time.
    conn, address = s.accept()
    print("Connected to: " + address[0] + ":" + str(address[1]))
    return conn

def GET():
    reply = storedValue
    return reply

def REPEAT(dataMessage):
    reply = dataMessage[1]
    return reply

def dataTransfer(conn):
    # A big loop that sends/receives data until told not to.
    while True:
        # Receive the data
        data = conn.recv(1024) # receive the data
        data = data.decode('utf-8')
        # Split the data such that you separate the command
        # from the rest of the data.
        dataMessage = data.split(' ', 1)
        command = dataMessage[0]
        if command == 'GET':
            reply = GET()
        elif command == 'REPEAT':
            reply = REPEAT(dataMessage)
        elif command == 'LED_ON':
            callLED()
            reply = 'LED was on'
        elif command == 'EXIT':
            print("Our client has left us :(")
            break
        elif command == 'KILL':
            print("Our server is shutting down.")
            s.close()
            break
        else:
            reply = 'Unknown Command'
        # Send the reply back to the client
        conn.sendall(str.encode(reply))
        print("Data has been sent!")
   # conn.close()


s = setupServer()

while True:
    try:
        conn = setupConnection()
        dataTransfer(conn)
    except Exception as ex:
        print(ex)
        break

这在我的Raspberry PI上运行。我从RPI启动服务器,然后在笔记本电脑上运行客户端程序,该程序可让我与服务器通信。它可以毫无问题地发送和接收数据,但是当我从笔记本电脑中关闭程序时,服务器终端会显示此信息,然后停止:Image Here

TCP客户端代码C#:

        const int PORT_NO = 5450;
        const string SERVER_IP = "RASPBERRY PI IP ";
        string textToSend;
        private void button3_Click(object sender, EventArgs e)
        {



            //---create a TCPClient object at the IP and port no.---
            TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
            NetworkStream nwStream = client.GetStream();
            byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);

            //---send the text---
            label2.Text = "Sending : " + textToSend;
            nwStream.Write(bytesToSend, 0, bytesToSend.Length);

            //---read back the text---
            byte[] bytesToRead = new byte[client.ReceiveBufferSize];
            int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
            textBox1.Text = "Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);         
            //client.Close();

        }

        private void SetMessage_Click(object sender, EventArgs e)
        {
            //---data to send to the server---
            textToSend = textBox2.Text;
            textBox2.Clear();

        }

对不起,我的英语不好

0 个答案:

没有答案