Python网络编程

TCP时间戳服务器

在python3中,进行发送的数据都进行encode操作,转化为字符,而输出的部分都进行decode转化为string。

server_tcp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/env python

from socket import *
from time import ctime

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

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

while True:
print('waiting for connection...')
tcpCliSock, addr = tcpSerSock.accept()
print('...connect from:', addr)

while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
response = '[%s] %s' % (bytes(ctime(), 'utf-8').decode('utf-8'), data.decode('utf-8'))
tcpCliSock.send(response.encode('utf-8'))

tcpCliSock.close()
tcpSerSock.close()

client_tcp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env python

from socket import *

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

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

# 用户无输入或者recv()方法调用失败,则跳出

while True:
data = input('> ')
if not data:
break
tcpCliSock.send(data.encode('utf-8'))
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print(data.decode('utf-8'))

tcpCliSock.close()

UDP时间戳服务器

server_udp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python

from socket import *
from time import ctime

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

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

while True:
print('waiting for message...')
#接收到的数据和地址
data, addr = udpSerSock.recvfrom(BUFSIZ)
response = '[%s] %s' % (bytes(ctime(), 'utf-8').decode('utf-8'), data.decode('utf-8'))
udpSerSock.sendto(response.encode('utf-8'), addr)
print('...received from and returned to: ', addr)

udpSerSock.close()

client_udp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python

from socket import *

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

udpCliSock = socket(AF_INET, SOCK_DGRAM)

while True:
data = input('> ')
if not data:
break
udpCliSock.sendto(data.encode('utf-8'), ADDR)
data, ADDR = udpCliSock.recvfrom(BUFSIZ)
if not data:
break
print(data.decode('utf-8'))

udpCliSock.close()