python socket编辑示例 tcp

服务端代码:

from socket import socket, AF_INET, SOCK_STREAM

# 1. 创建socket对象   AF_INET:用于internet之间的进程通信,SOCK_STREAM:表示TCP协议
server_socket = socket(AF_INET, SOCK_STREAM)

# 2. 绑定ip和端口号
ip = '127.0.0.1'
port = 8888
server_socket.bind((ip, port))

# 3. 开始监听 最大监听数量
server_socket.listen(5)
# print('服务器已经启动')

# 4. 等待客户端连接
clinic_socket, clinic_addr = server_socket.accept()

# 5. 接收客户端数据
data = clinic_socket.recv(1024).decode('utf-8')
while data != 'bye':
    if data != '':
        print("clinic:", data)
    inputData = input('serv:')
    clinic_socket.send(inputData.encode('utf-8'))  # 响应
    if inputData == 'bye':
        break
    data = clinic_socket.recv(1024).decode('utf-8')

# 关闭socket
clinic_socket.close()
server_socket.close()

客户端代码:

import socket

# 1. 创建对象
clinic_socket = socket.socket()

# 2. ip地址端口 连接
ip = '127.0.0.1'
port = 8888
clinic_socket.connect((ip, port))
# print('与服务器连接成功')

# 3. 发送数据
# clinic_socket.send('Welcome to python world'.encode('utf-8'))
info = ''  # 服务器接收到的数据
while info != 'bye':
    send_data = input('clinic:')
    clinic_socket.send(send_data.encode('utf-8'))
    if send_data == 'bye':
        break
    info = clinic_socket.recv(1024).decode('utf-8')
    print('serv:', info)

# 4. 关闭
clinic_socket.close()

示例结果:

 

posted @ 2024-08-23 10:05  龍飛鳯舞  阅读(2)  评论(0编辑  收藏  举报