python socket实现简单的(TCP/UDP)服务器/客户端

时间:2022-05-20 00:00:16

1、创建TCP服务端

# -*- coding: utf-8 -*-   
from socket import *
from time import ctime

HOST = 'localhost' #主机名
PORT = 9999 #端口号
BUFSIZE = 1024 #缓冲区大小1K
ADDR = (HOST,PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR) #绑定地址到套接字
tcpSerSock.listen(5) #监听 最多同时5个连接进来

while True: #无限循环等待连接到来
try:
print 'Waiting for connection ....'
tcpCliSock, addr = tcpSerSock.accept() #被动接受客户端连接
print u'Connected client from : ', addr

while True:
data = tcpCliSock.recv(BUFSIZE) #接受数据
if not data:
break
else:
print 'Client: ',data
tcpCliSock.send('[%s] %s' %(ctime(),data)) #时间戳

except Exception,e:
print 'Error: ',e
tcpSerSock.close() #关闭服务器

2、创建TCP客户端

# -*- coding: utf-8 -*-   
from socket import *

HOST = 'localhost' #主机名
PORT = 9999 #端口号 与服务器一致
BUFSIZE = 1024 #缓冲区大小1K
ADDR = (HOST,PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR) #连接服务器

while True: #无限循环等待连接到来
try:
data = raw_input('>')
if not data:
break
tcpCliSock.send(data) #发送数据
data = tcpCliSock.recv(BUFSIZE) #接受数据
if not data:
break
print 'Server: ', data
except Exception,e:
print 'Error: ',e

tcpCliSock.close() #关闭客户端

至此TCP的服务端和客户端已创建完毕!!

3、创建UDP服务器

    # -*- coding: utf-8 -*-   
from socket import *
from time import ctime

HOST = '127.0.0.1' #主机名
PORT = 9999 #端口号
BUFSIZE = 1024 #缓冲区大小1K
ADDR = (HOST,PORT)

udpSerSock = socket(AF_INET, SOCK_DGRAM)
udpSerSock.bind(ADDR) #绑定地址到套接字

while True: #无限循环等待连接到来
try:
print 'Waiting for message ....'
data, addr = udpSerSock.recvfrom(BUFSIZE) #接受UDP
print 'Get client msg is: ', data
udpSerSock.sendto('[%s] %s' %(ctime(),data), addr) #发送UDP
print 'Received from and returned to: ',addr

except Exception,e:
print 'Error: ',e
udpSerSock.close() #关闭服务器

4、创建UDP客户端

    # -*- coding: utf-8 -*-   
from socket import *

HOST = '127.0.0.1' #主机名
PORT = 9999 #端口号 与服务器一致
BUFSIZE = 1024 #缓冲区大小1K
ADDR = (HOST,PORT)

udpCliSock = socket(AF_INET, SOCK_DGRAM)

while True: #无限循环等待连接到来
try:
data = raw_input('>')
if not data:
break
udpCliSock.sendto(data, ADDR) #发送数据
data,ADDR = udpCliSock.recvfrom(BUFSIZE) #接受数据
if not data:
break
print 'Server : ', data

except Exception,e:
print 'Error: ',e

udpCliSock.close() #关闭客户端


推荐参考地址: 网络编程之套接字Socket、TCP和UDP通信实例