我正在尝试使用两种编程语言来实现套接字编程。我想将多个客户端与一台服务器连接,并且当客户端类型退出时,服务器应打印一条消息,并且客户端关闭连接。问题是我的Java客户端单独发送文本。例如,当客户端键入“退出”时,服务器将其获取为:
e
xit.
如何将它们作为一个字符串发送?因为如果服务器仅获得“ xit”,它将无法正常工作。
我尝试了两个“ DataOutputStream”函数”
1:writeBytes:用于分隔文本
2:writeUTF:服务器正确地考虑了文本,并且当客户端键入“退出”时,服务器将不执行条件。
此外,如何使服务器将消息广播到所有连接的客户端?
服务器代码:
import socket
import sys
import traceback
from threading import Thread
def main():
start_server()
def start_server():
host = "127.0.0.1"
port = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print("Server started and socket created")
try:
s.bind((host, port))
except:
print("Error!!: " + str(sys.exc_info()))
sys.exit()
s.listen(5) # maximum number of clients can connect to the server
print("Server is waiting for clients")
while True:
connection, address = s.accept()
ip, port = str(address[0]), str(address[1])
print("Server receives connection from " + ip + ":" + port)
try:
Thread(target=client_thread, args=(connection, ip, port)).start()
except:
print("Thread did not start.")
traceback.print_exc()
s.close()
def client_thread(connection, ip, port, max_buffer_size = 5120):
is_active = True
while is_active:
client_input = receive_input(connection, max_buffer_size)
if client_input == 'exit':
print("Client (" + port + ") want to close the connection and exit")
connection.close()
print("Connection " + ip + ":" + port + " closed")
is_active = False
else:
print("Client (" + port + ") said : " + format(client_input))
connection.sendall("-".encode("utf8"))
def receive_input(connection, max_buffer_size):
client_input = connection.recv(max_buffer_size)
client_input_size = sys.getsizeof(client_input)
if client_input_size > max_buffer_size:
print("The input size is greater than expected {}".format(client_input_size))
decoded_input = client_input.decode("utf8").rstrip() # decode and strip end of line
result = process_input(decoded_input)
return result
def process_input(input_str):
return str(input_str)
if __name__ == "__main__":
main()
使用Python中的客户端代码来了解我的想法:
import socket
import sys
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 8888
try:
s.connect((host, port))
except:
print("Connection error")
sys.exit()
print("To close the connection type (exit)")
message = input(" Type: ")
while True:
s.sendall(message.encode("utf8"))
if s.recv(5120).decode("utf8") == "-":
pass
message = input(" Type: ")
if message == 'exit':
s.send(message.encode("utf8"))
break;
s.close()
if __name__ == "__main__":
main()
我需要帮助的Java代码:
import java.net.*;
public class ClientJava {
public static void main(String argv[]) throws Exception {
String sentence;
String localhost = "127.0.0.1";
int port = 8888;
BufferedReader inData = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket(localhost, port);
DataOutputStream outData = new DataOutputStream(clientSocket.getOutputStream());
sentence = inData.readLine();
outData.writeBytes(sentence);
while (!sentence.equals("exit"))
{sentence = inData.readLine();
outData.writeBytes(sentence);
}
clientSocket.close();
}
}