You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Socket客户端代码报错求助:ValueError转换整数失败

Hey there, let's break down what's causing that error and fix your Python Socket client code step by step!

What's the Root Cause?

The error happens because your code assumes every message from the server starts with a 10-byte header that tells you the total length of the message. But in reality, the server is sending you a message that starts directly with You have c...—no numeric length header at all. When you try to convert that non-numeric string to an integer, Python throws the ValueError you're seeing.

On top of that, there's a small logic bug in your client code: line 12 sets new_msg = True right after parsing the header. That means every loop iteration will try to reparse a new header, which breaks the message collection flow.

Fixes for Your Code

We have two main paths here, depending on how your server is set up:

Option 1: If the Server Should Send a Length Header

If your plan is to use a 10-byte header to mark message lengths, you first need to make sure the server sends that header. Here's a quick example of what the server code should look like:

import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((socket.gethostname(), 4334))
server_socket.listen(5)

while True:
    client_socket, addr = server_socket.accept()
    actual_msg = "You have connected to the server!"
    # Create a 10-character header (pad with spaces to hit 10 chars)
    msg_length_header = f"{len(actual_msg):<10}"
    full_message_to_send = msg_length_header + actual_msg
    client_socket.send(full_message_to_send.encode("utf-8"))
    client_socket.close()

Then fix the logic bug in your client code (change new_msg = True to new_msg = False after parsing the header) and adjust the completion check to be accurate:

import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((socket.gethostname(),4334))
while True:
    full_msg = ''
    new_msg = True
    headersize = 10
    while True:
        msg = s.recv(10)
        if new_msg:
            print("new msg len:", msg[:headersize])
            # Use strip() to remove any padding spaces from the header
            msglen = int(msg[:headersize].strip())
            new_msg = False  # This was True before—fix it!
            print(f"full message length: {msglen}")
        full_msg += msg.decode("utf-8")
        print(len(full_msg))
        # Check if we've received the full header + message
        if len(full_msg) == headersize + msglen:
            print("full msg recvd")
            print(full_msg[headersize:])
            new_msg = True
            break  # Exit inner loop to wait for next message

Option 2: If the Server Sends Messages Directly (No Header)

If your server doesn't use a length header and just sends raw messages, you can simplify your client code entirely—no need for the header parsing logic:

import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((socket.gethostname(),4334))

while True:
    # Use a larger buffer (like 1024 bytes) to catch more of the message at once
    msg = s.recv(1024)
    if not msg:
        break  # Exit loop if the server closes the connection
    print("Received message:", msg.decode("utf-8"))
Quick Learning Tip

Socket programming lives and dies by protocol consistency—the client and server have to agree on exactly how messages are formatted (headers, encoding, length markers, etc.). Start with simple, header-free message passing to get the hang of basic connections, then work your way up to more complex length-based messaging once you're comfortable with the basics.

内容的提问来源于stack exchange,提问作者Tejas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 14:42:33