最简单的tcp客户端和服务端 还有udp
tcp服务器:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# -*- coding: utf-8 -*- """ Created on Tue May 26 21:39:55 2020 @author: Administrator """ import socket #创建套接字 tcp_server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #绑定IP和port address=('',8080) #listen使套接字变为可被动连接 tcp_server_socket.bind(address) tcp_server_socket.listen(128) #accept等待客户端链接 while True: client_addr,a=tcp_server_socket.accept() print(client_addr) #recv/send接收或发送数据 while True: recv_data=client_addr.recv(1024) print(recv_data) # 发过来数据会解堵塞 # 客户端关闭链接也会解堵塞此时为空 if recv_data: client_addr.send("服务器已收到".encode("utf-8")) else: client_addr.close() break tcp_server_socket.close()
tcp客户端:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# -*- coding: utf-8 -*- """ Created on Tue May 26 21:13:26 2020 @author: Administrator """ import socket #创建链接字 tcp_client_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #目的信息 server_ip="192.168.236.129" server_port=8080 #链接服务器 tcp_client_socket.connect((server_ip,server_port)) #提示用户输入数据 send_data="hello" #发送 tcp_client_socket.send(send_data.encode("utf-8")) #接受对方发过来的数据,最大1024 recvdata=tcp_client_socket.recv(1024) print(recvdata) #关闭连接 tcp_client_socket.close()
udp
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
## -*- coding: utf-8 -*- #""" #Created on Tue May 26 10:53:22 2020 # #@author: Administrator #""" # ##导入模块 #import socket ##创建socket #skt = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #skt.bind(('',8080)) #while True: # # #创建发送消息和发送目标 # msg = input() # addr = ('192.168.236.128',8080) # k=bytes(msg, encoding="utf8") # skt.sendto(k,addr) # ## 接收数据: # data = skt.recvfrom(1024) ## print(data) # s2 = str(data[0], encoding="UTF-8") # print(" "+s2) # #skt.close() #!/usr/bin/python3 import threading import time import socket class Server_Thread(threading.Thread): def __init__(self,threadID,name,skt): threading.Thread.__init__(self) self.threadID=threadID self.name=name self.skt=skt def run(self): while True: data = self.skt.recvfrom(1024) # print(data) s2 = str(data[0], encoding="UTF-8") print(" "+self.name+":"+s2) class Client_Thread(threading.Thread): def __init__(self,threadID,name,skt): threading.Thread.__init__(self) self.threadID=threadID self.name=name self.skt=skt def run(self): while True: #创建发送消息和发送目标 msg = input() addr = ('192.168.236.128',8080) k=bytes(msg, encoding="utf8") self.skt.sendto(k,addr) def main(): skt = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) skt.bind(('',8081)) # 创建新线程 thread1 = Client_Thread(1, "windows",skt) thread2 = Server_Thread(2, "linux",skt) # 开启新线程 thread1.start() thread2.start() thread1.join() thread2.join() skt.close() if __name__=="__main__": main()
-----------------------------------------------------------------------------------------------------------------------------------------