Python2数据传输测试脚本

服务端

# -*- coding: utf-8 -*-  
import socket  
import threading  
  
HOST = '0.0.0.0'  
PORT = 12345  
  
def handle_client(conn, addr):  
    print "连接地址:", addr  
    try:  
        while True:  
            data = conn.recv(1024000)  
            if not data:  
                break  
            print "收到", len(data), "字节的数据"  
            # 如果需要处理文本数据,这里应该添加解码操作  
            # data_str = data.decode('utf-8')  
    finally:  
        conn.close()  
  
def start_server():  
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
    s.bind((HOST, PORT))  
    s.listen(5)  
    print "服务器启动,等待连接..."  
  
    try:  
        while True:  
            conn, addr = s.accept()  
            client_thread = threading.Thread(target=handle_client, args=(conn, addr))  
            client_thread.start()  
    except KeyboardInterrupt:  
        print "服务器关闭"  
    finally:  
        s.close()  
  
if __name__ == '__main__':  
    start_server()

客户端

# -*- coding: utf-8 -*-  
import socket  
  
SERVER_IP = '192.168.200.128'  # 请替换为实际的服务器IP  
SERVER_PORT = 12345            # 请替换为服务器监听的端口  
  
def main():  
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
    try:  
        sock.connect((SERVER_IP, SERVER_PORT))  
        data = 'A' * 5000  
        sock.sendall(data)  
        print "发送", len(data), "字节的数据"
          
        # 如果需要接收服务器的响应,请取消注释以下两行  
        # response = sock.recv(1024)  
        # print 'Received:', repr(response)
    except Exception, e:
        print "发生错误:", e  
    finally:  
        sock.close()  
  
if __name__ == '__main__':  
    main()
posted @ 2024-09-04 09:52  wanghongwei-dev  阅读(4)  评论(0编辑  收藏  举报