#UDP
from threading import Thread
import socket
u=socket.socket(socket.AF_INET,socket.SOCK_DGRAM )
u.bind((“127.0.0.1”,8888))#绑定端口,用来接收数据
def sendnews():
while True:
data=input()
u.sendto(data.encode(“gbk”), (“127.0.0.1”,8888))
def recvnews():
while True:
data,ip=u.recvfrom (1024)
print(data.decode(“gbk”))
t1=Thread(target=sendnews,args=())
t2=Thread(target=recvnews,args=())
t1.start()
t2.start()
#TCP
#服务端
from threading import Thread
import socket
t=socket.socekt(socket.AF_INET,socket.SOCK_STREAM )
t.bind((“127.0.0.1”,8888))
b.listen(5)
def sendnews():
while True:
data=input()
new_t.send(data.encode(“gbk”))
def recvnews():
while True:
data=new_t.recv()
print(data.decode(“gbk”))
if __name__==”__main__”:
while True:
new_t,ip=t.accept()
t1=Thread(target=sendnews,args=())
t2=Thread(target=recvnews,args=())
t1.start()
t2.start()
#客户端
from threading import Thread
import socket
t=socket.socekt(socket.AF_INET,socket.SOCK_STREAM )
ipport=(“127.0.0.1”,8888)
t.connect(ipport)
def sendnews():
while True:
data=input()
t.send(data.encode(“gbk”))
def recvnews():
while True:
data= t.recv()
print(data.decode(“gbk”))
t1=Thread(target=sendnews,args=())
t2=Thread(target=recvnews,args=())
t1.start()
t2.start()
网友评论