我想在python中创建一个服务器和客户端。3这是我的服务器:
import socket
ip =('192.168.1.101',12345)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(ip)
s.listen(1)
print('Server is ready')
client , addr = s.accept()
print('one client has conected to me'+str(addr))
while True:
a = input('what do you want to tell ? ')
if a == 'q':
break
a=a.encode('utf_8')
client.sendall(a)
client.close()
我的客户是:
import socket
ip = ('192.168.1.101', 12345)
conecttion = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conecttion.connect(ip)
while True:
data = conecttion.recv(1024)
if data == 'q':
break
print(data)
conecttion.close()
但当我在客户端中发送'q'时,会使其成为无限循环。当我发送'q'时该怎么办?连接已关闭。谁能帮我。
两个问题:
- 在服务器上,您没有发送'q'。你在发送之前就坏了
- 在客户端上,接收到的数据是二进制的,因此需要转换为字符
试试这个代码:
服务器:
import socket
ip =('127.0.0.1',12345) # local machine
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(ip)
s.listen(1)
print('Server is ready')
client , addr = s.accept()
print('one client has conected to me'+str(addr))
while True:
a = input('what do you want to tell ? ')
aa=a.encode('utf_8')
client.sendall(aa) # byte data
if a == 'q': # original string
break
client.close()
客户:
import socket, time
ip = ('127.0.0.1', 12345) # local machine
conecttion = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conecttion.connect(ip)
while True:
data = conecttion.recv(1024)
if data and chr(data[0]) == 'q':
break
print(data)
conecttion.close()