Ubuntu启一个tcp server,client去连接

1、在~/source/code/python目录下创建两个py文件:

server_8079.py、client_8079.py

server_8079.py的代码:

python 复制代码
# server.py
import socket

def start_server(host, port):
    # 创建一个TCP/IP套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    # 绑定套接字到地址和端口
    server_socket.bind((host, port))
    
    # 监听传入连接
    server_socket.listen(1)
    print(f"Server listening on {host}:{port}")
    
    while True:
        # 等待连接
        client_socket, addr = server_socket.accept()
        try:
            print(f"Connection from {addr}")
            
            # 接收数据
            data = client_socket.recv(1024)
            print(f"Received: {data.decode('utf-8')}")
            
            # 发送响应
            response = "Hello from server!"
            client_socket.sendall(response.encode('utf-8'))
        finally:
            # 清理连接
            client_socket.close()

if __name__ == "__main__":
    HOST = '192.168.111.128'
    PORT = 8079
    start_server(HOST, PORT)

client_8079.py的代码:

python 复制代码
# client.py
import socket

def start_client(host, port):
    # 创建一个TCP/IP套接字
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    try:
        # 连接到服务器
        client_socket.connect((host, port))
        
        # 发送数据
        message = "Hello from client!"
        client_socket.sendall(message.encode('utf-8'))
        
        # 接收响应
        response = client_socket.recv(1024)
        print(f"Received: {response.decode('utf-8')}")
    finally:
        # 清理连接
        client_socket.close()

if __name__ == "__main__":
    HOST = '192.168.111.128'
    PORT = 8079
    start_client(HOST, PORT)

打开2个terminal:

在第1个terminal输入:

python3 server_8079.py

在第2个terminal输入:

python3 client_8079.py

相关推荐
zh1570235 小时前
JavaScript中WorkerThreads解决服务端计算瓶颈
jvm·数据库·python
代码AI弗森5 小时前
一文理清楚“算力申请 / 成本测算 / 并发评估”
java·服务器·数据库
蜡台6 小时前
Python包管理工具pip完全指南-----2
linux·windows·python
^—app5668666 小时前
游戏运存小启动不起来临时解决方法
运维·服务器
摇滚侠6 小时前
expdp 查看帮助
java·数据库·oracle
流年似水~6 小时前
MCP协议实战:从零搭建一个让Claude能“看见“数据库的工具服务
数据库·人工智能·程序人生·ai·ai编程
Ujimatsu6 小时前
虚拟机安装Debian 13.x及其常用软件(2026.4)
linux·运维·ubuntu
千百元6 小时前
zookeeper启不来了
linux·zookeeper·debian
2401_871492856 小时前
Vue.js监听器watch利用回调函数处理级联下拉框数据联动
jvm·数据库·python
志栋智能7 小时前
超自动化安全:构建智能安全运营的核心引擎
大数据·运维·服务器·数据库·安全·自动化·产品运营