普通版的socketserver
#server.py
import socket
sk = socket.socket()
sk.bind(('127.0.0.1',8080))#建立连接
sk.listen() #打开监听
while True:
conn,addr = sk.accept() #接收到一个连接和一个地址
ret = 'hi'.encode('utf-8')
conn.send(ret)
msg = conn.recv(1024).decode('utf-8')
print(msg)
conn.close()
sk.close()
#Client.py
import socket
sk = socket.socket()
sk.connect(('127.0.0.1',8080))
msg = sk.recv(1024).decode('utf-8')
print(msg)
msg2 = input('>>>').encode('utf-8')
sk.send(msg2)
sk.close()
简易多进程socketserver
```python
server.py
import socket
from multiprocessing import Process
主要的不同是利用了函数和子进程,这里建立了函数
def serve(conn):
ret = 'hi'.encode('utf-8')
conn.send(ret)
msg = conn.recv(1024).decode('utf-8')
print(msg)
conn.close()
if name == 'main':
sk = socket.socket()
sk.bind(('127.0.0.1',8080))#建立连接
sk.listen() #打开监听
while True:
conn,addr = sk.accept() #接收到一个连接和一个地址
开启子进程
p = Process(target=serve,args =(conn,))
p.start()
sk.close()
client.py
import socket
sk = socket.socket()
sk.connect(('127.0.0.1',8080))
msg = sk.recv(1024).decode('utf-8')
print(msg)
msg2 = input('>>>').encode('utf-8')
sk.send(msg2)
sk.close()