socket编程

服务端编程

新建 server.py 文件,添加如下代码:

import threading
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip_port = ('127.0.0.1', 211)
s.bind(ip_port)
s.listen(5)
con, address = s.accept()
print("%s 已连接" % address[0])
con.send('hello python'.encode())
isok = True


def rec(con):
   global isok
   while isok:
       recv_data = str(con.recv(1024), encoding="utf-8")
       if recv_data == 'exit':
           isok = False

       print(recv_data)


thrd = threading.Thread(target=rec, args=(con,))
thrd.start()

while isok:
   send_d = input("server>")
   con.sendall(bytes(send_d, encoding='utf-8'))
   if send_d == 'exit':
       isok = False

s.close()

客户端编程

新建client.py文件,添加如下代码:

import threading
import socket

cl = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip_port = ('127.0.0.1', 211)
cl.connect(ip_port)

isok = True


def rec(cl):
   global isok
   while isok:
       t = cl.recv(1024).decode("utf8")  # 客户端也同理
       if t == "exit":
           isok = False
       print(t)


th2 = threading.Thread(target=rec, args=(cl,))
th2.start()

while isok:
   t = input()
   cl.send(t.encode('utf8'))
   if t == "exit":
       isok = False
cl.close()

效果图

02-01 06:12