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

相关推荐
名字还没想好☜3 小时前
Python f-string 进阶:数字格式化、对齐填充、调试 = 号与嵌套表达式
开发语言·数据库·python·字符串格式化·f-string
ltl3 小时前
Serverless 数据库弹性理论:Neon 与 Aurora Serverless v2
数据库
ltl3 小时前
内核追踪:ftrace、kprobe、uprobe、tracepoint 生产实战
linux
·薯条大王3 小时前
经济实惠玩云服务器|一台云服务器多人共用,子账号配置教程
java·linux·运维·服务器·汇编·c++·python
ZJH__GO7 小时前
网络编程v4pro--实现聊天室文件传输功能
java·服务器·网络·计算机网络
小小、码农7 小时前
Linux进程控制:从fork到exec,手写一个简易Shell
linux·运维·服务器
不会就选b7 小时前
Linux之进程间通信(二)---模拟进程池
linux·运维·服务器
marvelyu8 小时前
每天10分钟学会OceanBase系列(Day 20):跨机房容灾实战——构建多数据中心高可用架构
java·大数据·数据库
NeilYuen8 小时前
用UDP实现向DNS服务器请求IP地址
服务器·tcp/ip·udp
ZCBUS实时计算8 小时前
金融证券实时数仓建设实践:轻量化实时计算平台落地,实现交易数据端到端秒级处理
大数据·数据库·数据仓库·金融·flink·dba·etl