简体   繁体   English

使用python从客户端向服务器发送数据

[英]Send data to server from client in python

import socket
import os
import msvcrt
import time

def timeInput(text="",e="",timeFin=0.01):
    result=[]
    done=time.time() +timeFin
    print(text,end=e)
    while 1:
        if msvcrt.kbhit():
            echo=msvcrt.getch().decode('ASCII')
            result.append(echo)
            time.sleep(0.1)
        else:
            if time.time() > done:
                st=""
                for i in result:
                    st=st+str(i)
                st=st.replace("`b","")
                return st



#username=("Username? ")

#x, y, width, height, username, map position, list position

try:
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect(('10.0.0.7', 25565))
    while 1:
        #data = client_socket.recv(512)
        #key=timeInput()

        #code="player,100,200,30,30,player2,0,1"
        code="chat,hi,Marc"
        client_socket.send(bytes(code,"UTF-8"))

except Exception as e:
    print("ERROR: "+str(e))

for some reason when I try connecting to my server in python, it connects properly but it won't continuously send chat,hi,Marc to the server. 由于某些原因,当我尝试使用python连接到服务器时,它可以正确连接,但不会继续向服务器发送chat,hi,Marc I have no clue why this is not working, thanks in advance! 我不知道为什么这不起作用,在此先感谢!

socket.send() does not guarantee that all bytes have been sent (or, better said, that all bytes have been copied to the outgoing buffer). socket.send()不能保证所有字节都已发送(或者更好的说,所有字节都已复制到输出缓冲区)。 send() blocks until at least one character can be sent. send()阻塞,直到可以发送至少一个字符为止。

You are probably filling the out buffer fast because of the loop, and then adding some parts of the message, then blocking until some buffer space is released. 您可能由于循环而快速填充了out缓冲区,然后添加了消息的某些部分,然后阻塞直到释放了一些缓冲区空间。

So, you need to read the result of send(). 因此,您需要读取send()的结果。 If it is > 0, that's how many bytes you've sent, so you have to send() again the remaining part. 如果它大于0,则表示已发送了多少字节,因此必须再次发送send()剩余部分。 If send() returns <= 0, connection is closed and you should exit the loop. 如果send()返回<= 0,则连接已关闭,您应该退出循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM