网络编程
1、基于 TCP 的套接字:
服务端:
import socket phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #tcp协议 # phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) phone.bind(('127.0.0.1',8083)) #0-65535 phone.listen(5) print('starting...') while True: #链接循环 conn,client_addr=phone.accept() # print(conn,client_addr) print(client_addr) while True: #通信循环 try: data=conn.recv(1024) #1024bytes? if not data:break #针对的是linux系统 print('客户端消息',data) conn.send(data.upper()) except ConnectionResetError:#针对的是windows系统 break conn.close() phone.close()
客户端:
import socket phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #tcp协议 phone.connect(('127.0.0.1',8083)) #0-65535 while True: msg=input('>>: ').strip() if not msg:continue phone.send(msg.encode('utf-8')) data=phone.recv(1024) print(data) phone.close()
2、基于 UCP 的套接字
服务端:
#_*_coding:utf-8_*_
import socket
ip_port=('127.0.0.1',9000)
BUFSIZE=1024
udp_server_client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #数据报协议
udp_server_client.bind(ip_port)
while True:
msg,addr=udp_server_client.recvfrom(BUFSIZE)
print(msg,addr)
udp_server_client.sendto(msg.upper(),addr)
客户端:
#_*_coding:utf-8_*_
import socket
ip_port=('127.0.0.1',9000)
BUFSIZE=1024
udp_server_client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while True:
msg=input('>>: ').strip()
if not msg:continue
udp_server_client.sendto(msg.encode('utf-8'),ip_port)
back_msg,addr=udp_server_client.recvfrom(BUFSIZE)
print(back_msg.decode('utf-8'),addr)
3、SocketServer 模块:
#服务端TCP import socketserver class MyTCPhandler(socketserver.BaseRequestHandler): #requests来解决通信问题 def handle(self): #必须是handle这个名字 #print('==>',self) #客户端连接就打印一个对象 while True: #conn.recv(1024) data=self.request.recv(1024) #self.request 就是conn self.request.send(data.upper()) if __name__ == '__main__': #print(socketserver.ForkingTCPServer) #windows没有fork这个模块,不能在windows开进程,linux可以 s=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyTCPhandler) #server来解决链接问题 s.serve_forever() #一直提供服务
#服务端udp import socketserver class MyTCPhandler(socketserver.BaseRequestHandler): def handle(self): print(self.request) #打印一个元组,第一个元素是数据,第二个元素是服务端的套接字s=socket(AF_INET,SOCK_DGRAM) client_data=self.request[0] self.request[1].sendto(client_data.upper(),self.client_address) if __name__ == '__main__': s=socketserver.ThreadingUDPServer(('127.0.0.1',8080),MyTCPhandler) s.serve_forever()
#客户端TCP #和之前一样
from socket import *
c=socket(AF_INET,SOCK_STREAM)
c.connect(('127.0.0.1',8080))
while True:
msg=input('>>: ').strip()
if not msg:break
c.send(msg.encode('utf-8'))
data=c.recv(1024)
print(data)
c.close()
#客户端UDP #和之前一样
from socket import *
c=socket(AF_INET,SOCK_DGRAM)
while True:
msg=input('>>: ').strip()
if not msg:break
c.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
data=c.recvfrom(1024)
print(data)
c.close()