基于python的socket库,用tcp协议实现局域网聊天
服务器端
from socket import *
from threading import Thread
import time
IP='0.0.0.0'#全部开放
PORT=50000
BUFLEN=512
listenSocket=socket(AF_INET,SOCK_STREAM)
listenSocket.bind((IP,PORT))
listenSocket.listen(5)
print(f'success,waiting for {PORT}')
dataSocket,addr=listenSocket.accept()
print('connect one',addr)
class get(Thread):
def run(self):
while True:
time.sleep(1)
recved = dataSocket.recv(BUFLEN)
if not recved:
break
info = recved.decode()
print(' << '+info+'\n>>',end='')
class send(Thread):
def run(self):
while True:
info = input('>>')
dataSocket.send(info.encode())
if __name__ == '__main__':
send().start()
get().start()
客户端
import os,sys
import time
from socket import *
from threading import Thread
IP='略'#服务器ip
SERVER_PORT=50000
BUFLEN=512
print("he isn't here")
while True:
try:
time.sleep(5)
dataSocket=socket(AF_INET,SOCK_STREAM)
dataSocket.connect((IP,SERVER_PORT))
break
except:
pass
class send(Thread):
def run(self):
while True:
toSend = input(">>")
if toSend == '':
break
dataSocket.send(toSend.encode())
class get(Thread):
def run(self):
while True:
time.sleep(1)
recved = dataSocket.recv(BUFLEN)
if not recved:
break
print(' << '+recved.decode()+'\n>>',end='')
if __name__ == '__main__':
os.system("cls")
print("you have connected him")
send().start()
get().start()
veryvery欢迎提建议