我正在尝试在服务器和客户端之间创建python聊天室。到目前为止,客户端和服务器之间的通信已按预期进行。我还打算在客户端和服务器之间添加文件共享功能。到目前为止,如果键入了关键字文件,然后指定了文件名,则可以将文件从服务器发送到客户端,并且可以使客户端侦听并接收此文件。但是,我也希望客户端能够发送文件。服务器在侦听文件时出现问题。以及客户端能够发送文件。这是代码。有一个服务器文件和一个客户端文件。在此先感谢!
//server side
import time, socket, sys
print('Setup Server...')
time.sleep(1)
#Get the hostname, IP Address from socket and set Port
soc = socket.socket()
host_name = socket.gethostname()
ip = socket.gethostbyname(host_name)
port = 1234
soc.bind((host_name, port))
print(host_name, '({})'.format(ip))
name = input('Enter name: ')
soc.listen(1) #Try to locate using socket
print('Waiting for incoming connections...')
connection, addr = soc.accept()
print("Received connection from ", addr[0], "(", addr[1], ")\n")
print('Connection Established. Connected From: {}, ({})'.format(addr[0], addr[0]))
#get a connection from client side
client_name = connection.recv(1024)
client_name = client_name.decode()
print(client_name + ' has connected.')
print('Press [bye] to leave the chat room')
print('Press picture to send picture')
connection.send(name.encode())
while True:
message = input('Me > ')
if message == '[bye]':
message = 'Good Night...'
connection.send(message.encode())
print("\n")
break
if message == 'picture':
filename = input(str("Please enter the filename of the file : "))
file = open (filename, 'rb')
file_data = file.read(999999)
connection.send(file_data)
print("Data has been transmitted Successful!")
connection.send(message.encode())
message = connection.recv(999999)
message = message.decode()
print(client_name, '>', message)
//client side
import time, socket, sys
print('Client Server...')
time.sleep(1)
#Get the hostname, IP Address from socket and set Port
soc = socket.socket()
shost = socket.gethostname()
ip = socket.gethostbyname(shost)
#get information to connect with the server
print(shost, '({})'.format(ip))
server_host = input('Enter server\'s IP address:')
name = input('Enter Client\'s name: ')
port = 1234
print('Trying to connect to the server: {}, ({})'.format(server_host, port))
time.sleep(1)
soc.connect((server_host, port))
print("Connected...\n")
soc.send(name.encode())
server_name = soc.recv(1024)
server_name = server_name.decode()
print('{} has joined...'.format(server_name))
print('Enter [bye] to exit.')
file = open("client_side.PNG", 'wb')
file_data = soc.recv(999999)
file.write(file_data)
file.close()
print("File has been received successfully.")
while True:
message = soc.recv(1024)
message = message.decode()
print(server_name, ">", message)
message = input(str("Me > "))
if message == "[bye]":
message = "Leaving the Chat room"
soc.send(message.encode())
print("\n")
break
soc.send(message.encode())