今天,就给大家带来一篇利用Python3.6实现的Socket编程,这里列举一个TCP实例和UDP实例,同时,利用encode()和decode()对网络消息进行编码和解码操作。

实例说明:TCP实例和UDP实例实现的功能均如下:

1)客户端对发送的消息进行编码(encode())后发送到服务端

2)服务端接收客户端发来的消息

3)服务端对接收的消息解码(decode())

4)服务端拼接客户端发来的消息(格式为:[时间]+客户端发来的消息)

5)服务端对拼接后的消息进行编码(encode())后发送给客户端

6)客户端接收服务端发送的消息,解码(decode())并打印出来

一、TCP实例

1、TCP服务端

'''
Created on 2018年4月16日

@author: liuyazhuang
'''
from socket import *
from time import ctime

HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcp_server_socket = socket(AF_INET, SOCK_STREAM)
tcp_server_socket.bind(ADDR)
tcp_server_socket.listen(5)

while True:
print("waiting for connecting...")
tcp_client_socket, addr = tcp_server_socket.accept()
print("...connected from addr: ", addr)

while True:
data = tcp_client_socket.recv(BUFSIZ).decode()
if not data:
break
tcp_client_socket.send(('[%s] %s' %(ctime(),data)).encode())

tcp_client_socket.close()
tcp_server_socket.close()

2、TCP客户端

'''
Created on 2018年4月16日

@author: liuyazhuang
'''
from socket import *

HOST = "127.0.0.1"
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcp_client_socket = socket(AF_INET, SOCK_STREAM)
tcp_client_socket.connect(ADDR)

while True:
data = input('> ')
if not data:
break;
tcp_client_socket.send(data.encode())
data = tcp_client_socket.recv(BUFSIZ).decode()
if not data:
break;
print(data)
tcp_client_socket.close()

二、UDP实例

1、UDP服务端

'''
Created on 2018年4月16日

@author: liuyazhuang
'''
from socket import *
from time import ctime

HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

udp_server_socket = socket(AF_INET, SOCK_DGRAM)
udp_server_socket.bind(ADDR)

while True:
print('waiting for message...')
data, addr = udp_server_socket.recvfrom(BUFSIZ)
data = data.decode()
udp_server_socket.sendto(('[%s] %s' %(ctime(),data)).encode(), addr)
print("...received from and sent to: " , addr)

udp_server_socket.close()

2、UDP客户端

'''
Created on 2018年4月16日

@author: liuyazhuang
'''
from socket import *

HOST = '127.0.0.1'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

udp_client_socket = socket(AF_INET, SOCK_DGRAM)
while True:
data = input("> ")
if not data:
break;
udp_client_socket.sendto(data.encode(), ADDR)
data, addr = udp_client_socket.recvfrom(BUFSIZ)
if not data:
break;
data = data.decode()
print(data)

udp_client_socket.close()