Python网络通信
服务器
import socket
server_address=('127.0.0.1',5578)
user_limit=int(8)
def main():
tcp_server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcp_server.bind(server_address)
tcp_server.listen(user_limit)
#Wait until Connection
client,client_address=tcp_server.accept()
print('Connection From',client_address)
while True:
#Wait until Recv One Byte
recv_type=client.recv(1)
#Connection Closed
if len(recv_type)==0:
print('Connection Lost')
break
recv_type=int.from_bytes(recv_type,byteorder='big',signed=False)
if recv_type==0:
print('Client Quit')
break
elif recv_type==1:
recv_len=client.recv(1)
#Should be Same with Client
recv_len=int.from_bytes(recv_len,byteorder='big',signed=False)
recv_message=client.recv(recv_len)
recv_message=recv_message.decode('utf-8')
print(recv_message)
client.close()
if __name__=='__main__':
main()
客户端
import socket
server_address=('127.0.0.1',5578)
def main():
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.connect(server_address)
print('Connect Finished')
while True:
message=input('')
if message=='Q':
mess_type=int(0)
mess_type=mess_type.to_bytes(1,byteorder='big',signed=False)
server.sendall(mess_type)
break
else:
mess_type=int(1)
mess_type=mess_type.to_bytes(1,byteorder='big',signed=False)
message=message.encode('utf-8')
message_len=len(message)
message_len=message_len.to_bytes(1,byteorder='big',signed=False)
server.sendall(mess_type+message_len+message)
server.close()
if __name__=='__main__':
main()