网络编程:socket--python核心编程(3),chapter 1
最近两天把第一部分的网络编程socket好好学习了一番,收获也蛮多的。。。
套接字:能使运行在不同或相同计算机上运行的进行通信;套接字一种是基于文件的(同一台计算机进程间通信),另一种是基于网络的(同一台或不同计算机进程通信),经常使用的是AF_INET
套接字又分:无连接的 和 面向连接的;面向连接的套接字,也就是我们常说的tcp连接;无连接的套接字,就是udp;因为基于网络的所以就要通过ip协议来进行传输,所以下面是通过socket来创建udp和tcp连接:
tcp:tcptest = socket.socket(AF_INET,SOCK_STREAM) tcp:流套接字,SOCK_STREAM
udp: udptest = socket.socket(AF_INET,SOCK_DGRAM) udp:数据报(datagram),SOCK_DGRAM
下面将分别使用tcp和udp进行传输,包括服务端和客户端(本次测试:服务端和客户端都是在本机)
1、tcp创建服务器和客户端,常用的方法:s.bind()、s.listen()、s.accept()、s.connect()、s.recv()、s.send()
s.bind():将地址和端口绑定到套接字上;s.listen():设置并启动监听器;s.accept():接收tcp客户端连接
s.connect():tcp客户端连接服务器;s.recv():接收tcp消息;s.send():发送tcp消息
a:TCP服务器:TcpServer.py
1 #coding=utf-8 2 3 """ 4 author : xiaoshitou 5 date : 2016-08-08 6 """ 7 from socket import * 8 from time import ctime 9 10 host = '127.0.0.1' 11 port = 2000 12 bufsiz = 1024 13 addr = (host, port) 14 15 tcpServer = socket(AF_INET, SOCK_STREAM) 16 tcpServer.bind(addr) 17 tcpServer.listen(5) 18 19 while True: 20 print 'TCP...waiting for connection...' 21 tcpClientSock, addr = tcpServer.accept() 22 print 'TCP...connected from: {0}'.format(addr,) 23 24 while True: 25 data = tcpClientSock.recv(bufsiz) 26 if not data: 27 break 28 tcpClientSock.send('TCP: {0}: {1}'.format(ctime(), data)) 29 30 tcpClientSock.close() 31 tcpServer.close()
b:TcpClient.py
1 #coding=utf-8 2 3 """ 4 author : xiaoshitou 5 date : 2016-08-09 6 """ 7 from socket import * 8 9 host = '127.0.0.1' 10 port = 2000 11 bufsiz = 1024 12 addr = (host, port) 13 14 tcpclient = socket(AF_INET,SOCK_STREAM) 15 tcpclient.connect(addr) 16 17 while True: 18 data = raw_input('> ') 19 if not data: 20 break 21 tcpclient.send(data) 22 data = tcpclient.recv(bufsiz) 23 if not data: 24 break 25 print data 26 27 tcpclient.close()
执行结果:
2、udp创建服务器和客户端,常用方法:s.recvfrom():接收udp消息;s.sendto():发送udp消息
a、UdpServer.py
1 #coding=utf-8 2 3 """ 4 author : xiaoshitou 5 date : 2016-08-09 6 """ 7 from socket import * 8 from time import ctime 9 10 host = '127.0.0.1' 11 port = 2000 12 bufsiz = 1024 13 addr = (host, port) 14 15 udpserver = socket(AF_INET, SOCK_DGRAM) 16 udpserver.bind(addr) 17 18 while True: 19 print 'UDP...waiting for message...' 20 data, addr = udpserver.recvfrom(bufsiz) 21 udpserver.sendto('UDP: {0}: {1}'.format(ctime(), data), addr) 22 print 'UDP...received from and returned to: {0}'.format(addr,) 23 24 udpserver.close()
b、UdpClient.py
1 #coding=utf-8 2 3 """ 4 author : xiaoshitou 5 date : 2016-08-09 6 """ 7 from socket import * 8 from time import ctime 9 10 host = '127.0.0.1' 11 port = 2000 12 bufsiz = 1024 13 addr = (host, port) 14 15 udpclient = socket(AF_INET,SOCK_DGRAM) 16 17 while True: 18 data = raw_input('> ') 19 if not data: 20 break 21 udpclient.sendto(data, addr) 22 data, addr = udpclient.recvfrom(bufsiz) 23 if not data: 24 break 25 print data 26 27 udpclient.close()
udp服务端和客户端执行结果: