服务端
import socket
from multiprocessing import Process
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('127.0.0.1', 8080))
s.listen(5)
class Communicate(Process):
def __init__(self, conn):
super().__init__()
self.conn = conn
def run(self):
while 1:
try:
data = self.conn.recv(1024)
if not data: break
self.conn.send(data.upper())
except Exception:
break
self.conn.close()
if __name__ == '__main__':
while 1:
conn, addr = s.accept()
p = Communicate(conn)
p.start()
s.close()
客户端
import socket
c = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
c.connect(('127.0.0.1',8080))
while 1:
msg = input('>>:').strip()
if not msg:continue
c.send(msg.encode('utf-8'))
data = c.recv(1024)
print(data.decode('utf-8'))
c.close()