Python网络通信

1、创建服务器

import socket
import threading

def send(lists,client:socket.socket):
    while 1:
        b = client.recv(1024)
        for i in lists:
            i.send(b)


server = socket.socket()
server.bind(("127.0.0.1",1234))
server.listen(10)
l = []
while True:
    clineSc, clineIp = server.accept()
    print(f"客服端链接:{clineIp}")
    l.append(clineSc)
    threading.Thread(target=send,args=(l,clineSc,)).start()

server.close()

2、创建客服端

import socket
import _thread
import time

def send(s:socket.socket):
    while True:
        data=input("请输入您要发送的内容:")
        s.send(bytes(data,encoding="utf-8"))

def recv(r: socket.socket):
    while True:
        b=r.recv(1024)
        print("\r\n服务器发来的内容:"+str(b,encoding="utf-8"))

cline = socket.socket()
cline.connect(("192.168.0.115",1234))
_thread.start_new_thread(send,(cline,))
_thread.start_new_thread(recv,(cline,))
time.sleep(100)
cline.close()

你可能感兴趣的:(技术型,python)