1. tcp_server.py
  2. tcp_client.py
  3. udp_server.py
  4. udp_client.py

整理Python官网给的sample:https://docs.python.org/3/library/socket.html

官网展示了支持IPv4的TCP代码,这里也展示UDP的代码,两者基本类似。

tcp_server.py

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
# Echo server program
from socket import *
from time import ctime

HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
BUFSIZE = 1024
ADDR = (HOST, PORT)

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

while True:
print('waiting for connection...')
tcpClientSocket, address = tcpServerSocket.accept()
print('...connected by', address)

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

tcpClientSocket.close()
tcpServerSocket.close()

tcp_client.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Echo client program
from socket import *

HOST = '127.0.0.1'
PORT = 50007 # The same port as used by the server
BUFSIZE = 1024
ADDR = (HOST, PORT)

tcpClientSocket = socket(AF_INET, SOCK_STREAM)
tcpClientSocket.connect(ADDR)
print('connected to', ADDR)
while True:
data = input('> ')
if not data:
break
tcpClientSocket.send(data.encode())
data = tcpClientSocket.recv(BUFSIZE).decode()
if not data:
break
print(data)

tcpClientSocket.close()

udp_server.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Echo server program
from socket import *
from time import ctime

HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
BUFSIZE = 1024
ADDR = (HOST, PORT)

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

while True:
print('waiting for message...')
data, address = udpServerSocket.recvfrom(BUFSIZE)
data = data.decode()
print('...received from', address)
print(data)
udpServerSocket.sendto(('[%s] %s' %(ctime(), data)).encode(), address)

udpServerSocket.close()

udp_client.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Echo client program
from socket import *

HOST = '127.0.0.1'
PORT = 50007 # The same port as used by the server
BUFSIZE = 1024
ADDR = (HOST, PORT)

while True:
udpClientSocket = socket(AF_INET, SOCK_DGRAM)
udpClientSocket.connect(ADDR)
data = input('> ')
if not data:
break
udpClientSocket.send(('%s\r\n' % data).encode())
data = udpClientSocket.recv(BUFSIZE).decode()
if not data:
break
print(data)

udpClientSocket.close()