TCP编程UDP编程

客户端

# 导入socket库:
import socket
#socket.AF_INET 表示ip4,SOCK_STREAM流的形式
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接:
s.connect(('127.0.0.1', 9999))
# 接收欢迎消息:
print(s.recv(1024).decode('utf-8'))
for data in [b'Michael', b'Tracy', b'Sarah']:
    # 发送数据:
    s.send(data)
    print(s.recv(1024).decode('utf-8'))
s.send(b'exit')
s.close()

服务端

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 监听端口:
s.bind(('127.0.0.1', 9999))
#5表示最大连接数量
s.listen(5)
#接下来,服务器程序通过一个永久循环来接受来自客户端的连接,accept()会等待并返回一个客户端的连接:
print('Waiting for connection...')
while True:
    # 接受一个新连接:
    sock, addr = s.accept()
    # 创建新线程来处理TCP连接:
    t = threading.Thread(target=tcplink, args=(sock, addr))
    t.start()
#每个连接都必须创建新线程(或进程)来处理,否则,单线程在处理连接的过程中,无法接受其他客户端的连接:
def tcplink(sock, addr):
    print('Accept new connection from %s:%s...' % addr)
    sock.send(b'Welcome!')
    while True:
        data = sock.recv(1024)
        time.sleep(1)
        if not data or data.decode('utf-8') == 'exit':
            break
        sock.send(('Hello, %s!' % data.decode('utf-8')).encode('utf-8'))
    sock.close()
    print('Connection from %s:%s closed.' % addr)
TCP编程UDP编程_第1张图片
Paste_Image.png

UDP

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import socket

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

for data in [b'Michael', b'Tracy', b'Sarah']:

# 发送数据:

s.sendto(data, ('127.0.0.1', 9999))

# 接收数据:

print(s.recv(1024).decode('utf-8'))

s.close()
#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import socket

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

# 绑定端口:

s.bind(('127.0.0.1', 9999))

print('Bind UDP on 9999...')

while True:

# 接收数据:

data, addr = s.recvfrom(1024)

print('Received from %s:%s.' % addr)

reply = 'Hello, %s!' % data.decode('utf-8')

s.sendto(reply.encode('utf-8'), addr)
TCP编程UDP编程_第2张图片
Paste_Image.png

你可能感兴趣的:(TCP编程UDP编程)