请教一个关于python socket的问题
发布网友
发布时间:2022-04-22 23:41
我来回答
共1个回答
热心网友
时间:2022-05-07 16:48
代码如下:
Python code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/python
from socket import socket, AF_INET, SOCK_STREAM
from threading import Thread
port = 50008
host = 'localhost'
def server():
sock = socket(AF_INET, SOCK_STREAM)
sock.bind(('', port))
sock.listen(5)
while True:
conn, addr = sock.accept()
data = conn.recv(1024)
reply = 'server got: [%s]' % data
conn.send(reply.encode())
def client(name):
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port))
sock.send(name.encode())
reply = sock.recv(1024)
sock.close()
print('client got: [%s]' % reply)
if __name__ == '__main__':
sthread = Thread(target=server)
sthread.daemon = True
sthread.start()
for i in range(5):
Thread(target=client, args=('client%s' % i,)).start()
在ubuntu下运行,报下面的异常信息:
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.2/threading.py", line 740, in _bootstrap_inner
self.run()
File "/usr/lib/python3.2/threading.py", line 693, in run
self._target(*self._args, **self._kwargs)
File "./socket_test.py", line 21, in client
sock.connect((host, port))
socket.error: [Errno 111] Connection refused
把socket绑定的端口改为5000后,就没有异常。
client got: [server got: [client1]]
client got: [server got: [client0]]
client got: [server got: [client2]]
client got: [server got: [client3]]
client got: [server got: [client4]]
我这正常的,你那是不是有两个服务器同时开了?把原来那个杀掉。