请努力创建一个简单的代码,我希望这一行代码本质上是一个代码,其中文件处理txt文件中连接到服务器的ip地址
我以前曾尝试过这样做,但无济于事
#server
import socket
import select
IP = "127.0.0.1"
PORT = 4000
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((IP, PORT))
server_socket.listen()
sockets_list = [server_socket]
HEADER_LENGTH = 7
users = {}
print(f'\nWaiting for Client Connections via {IP}:{PORT}...')
# Handles message receiving
def msg_handling(user_socket):
try:
msg_h = user_socket.recv(HEADER_LENGTH)
if not len(msg_h):
return False
msg_l = int(msg_h.decode('utf-8').strip())
return {'header': msg_h, 'data': user_socket.recv(msg_l)}
except:
return False
while True:
identify_sockets, _, accept_sockets = select.select(sockets_list, [], sockets_list)
for identified_socket in identify_sockets:
if identified_socket == server_socket:
user_socket, user_address = server_socket.accept()
user = msg_handling(user_socket)
if user is False:
continue
sockets_list.append(user_socket)
users[user_socket] = user
print('NEW CONNECTION
rom {}:{}, username: {}'.format(*user_address, user['data'].decode('utf-8')))
else:
msg = msg_handling(identified_socket)
if msg is False:
print('CLOSED CONNECTION from: {}'.format(users[identified_socket]['data'].decode('utf-8')))
sockets_list.remove(identified_socket)
del users[identified_socket]
continue
user = users[identified_socket]
print(f'Received message from {user["data"].decode("utf-8")}: {msg["data"].decode("utf-8")}')
for user_socket in users:
if user_socket != identified_socket:
user_socket.send(user['header'] + user['data'] + msg['header'] + msg['data'])