python socket实现客户端和服务端

利用python socket和threading实现简单的客户端和服务端

tcp_server.py

#!usr/bin/python
# -*- coding:utf8 -*-
import socket
import threading


# 处理客户端的请求操作
def handle_client_request(service_client_socket, ip_port):
    while True:
        recv_data = service_client_socket.recv(1024)
        if recv_data:
            print(recv_data.decode('utf8'), ip_port)
            service_client_socket.send('ok, 问题正在处理中...'.encode('utf8'))
        else:
            print('客户端下线了:', ip_port)
            break
    service_client_socket.close()


if __name__ == '__main__':
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 设置端口复用
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    tcp_server_socket.bind(('', 9000))
    # 最大等待连接数为128
    tcp_server_socket.listen(128)
    while True:
        service_client_socket, ip_port = tcp_server_socket.accept()
        print('客户端连接成功', ip_port)
        sub_thread = threading.Thread(target=handle_client_request, args=(service_client_socket, ip_port))
        # 设置守护线程
        sub_thread.setDaemon(True)
        sub_thread.start()
    # tcp_server_socket.close()

我们可以看到对于每一个连接请求,都会创建一个线程来处理这个请求

tcp_client.py

#!usr/bin/python
# -*- coding:utf8 -*-
import socket 


if __name__ == '__main__':
    tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_client_socket.connect(('127.0.0.1', 9000))
    send_data = '你好服务端, 我是客户端小黑!'.encode('utf8')
    tcp_client_socket.send(send_data)
    recv_data = tcp_client_socket.recv(1024)
    print(recv_data)
    recv_content = recv_data.decode('utf8')
    print('接受服务端的数据为:', recv_content)
    tcp_client_socket.close()

这里我们使用的是基于tcp协议的socket,注意是基于字节流的,所以不要忘记编码.

你可能感兴趣的:(Python)