Вот код моего 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, а затем запускаю клиентскую программу на своем ноутбуке, которая позволяет мне общаться с сервером. Он отправляет и получает данные без каких-либо проблем, но когда я закрываю программу со своего ноутбука, серверный терминал показывает это и затем останавливается: Изображение здесь
Код клиента 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();
}
Извините за мой плохой английский sh