TCP

TCP-Client

1
2
3
4
5
6
7
8
9
10
11
12
13
import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("127.0.0.1", 50002))

send_data = "haha, text 01"
client.send(send_data.encode())
print("Client SEND: " + send_data)

recv_data = client.recv(4096).decode()
print("Client RECV: " + recv_data)

client.close()

TCP-Server

1
2
3
4
5
6
7
8
9
10
11
12
13
import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("", 50002))
server.listen(1)

connection, addr = server.accept()
if connection:
recv_data = connection.recv(4096).decode()
print("Server RECV: " + recv_data)

send_data = "Server ACK -> " + recv_data
connection.send(send_data.encode())

UDP

UDP-Client

1
2
3
4
5
6
7
8
9
10
import socket

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

send_data = "client udp data 01"
client.sendto(send_data.encode(), ("127.0.0.1", 60001))
print("Client SEND: " + send_data)

recv_data, addr = client.recvfrom(4096)
print("Client RECV: " + recv_data.decode())

UDP-Server

1
2
3
4
5
6
7
8
9
10
11
12
import socket

server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(("", 60001))

recv_data, addr = server.recvfrom(4096)
print("Server RECV: " + recv_data.decode())

if recv_data:
send_data = "Server ACK -> " + recv_data.decode()
server.sendto(send_data.encode(), addr)
print("Server SEND: " + send_data)

笔记

  1. Server端先启动,在某一公认地址上开放一个端口,即代码中的 server.bind(), 等待Client的请求到达该端口。
    Client端启动后,创建socket,通过Server端开放的地址和端口进行连接(TCP)或者发送数据(UDP),即代码中的 client.connect()client.sendto()
  2. socket地址描述
    socket.AF_INET: 将使用标准的IPv4地址或者主机名
  3. socket类型
    socket.SOCK_STREAM: 有序的、可靠的、双向的和基于连接的字节流,使用带外数据传送机制,TCP
    socket.SOCK_DGRAM: 无连接的、不可靠的和使用固定大小(通常很小)缓冲区的数据报服务, UDP



Published with Hexo and Theme by Kael
X