简体   繁体   English

Python:套接字编程的.send函数

[英]Python: .send function of socket programming

I send some message 'hello' from client to server using this command on server 我使用服务器上的此命令从客户端向服务器发送一些消息“ hello”

    #Send some data to remote server
    message = 'hello'

    try :

    s.send(message)
    print 'data sent successfully'
    except socket.error:
    #Send failed
    print 'Send failed'

Now on server side , I want to check whether this message is present as a key in dictionary which is created on server side. 现在在服务器端,我想检查此消息是否作为在服务器端创建的字典中的键出现。

    msg=c.recvfrom(1024)

     if msg in data2.keys():
 print("key for this msg exists", msg)
     else:
     print("no such key exists",msg)

Now, the problem is it always says no such key exits. 现在的问题是,它总是说没有这样的键退出。 When I print the msg on server side which I have got from client.It comes out to be: 当我从客户端获得服务器端的味精时,结果是:

   ('hello', None)

I don't get it why it gives None along with hello. 我不明白为什么它会给None和您好。

because of this I am not even getting a match in dictionary. 因此,我什至没有在字典中找到匹配项。 Please tell me where I am doing wrong. 请告诉我我在哪里做错了。

As the documentation for socket states: The return value is a pair (string, address) where string is a string representing the data received and address is the address of the socket sending the data. 作为套接字状态的文档,请执行以下操作: 返回值是一个对(字符串,地址),其中string是表示接收到的数据的字符串,而address是发送数据的套接字的地址。

So your ('hello', None) is this pair and if you want to pick the message string from it to search it in your dict, you have to use msg[0] . 因此,您的('hello', None)就是这对,如果您要从中选择消息字符串以在字典中对其进行搜索,则必须使用msg[0]

If you look at the documentation for socket.recvfrom() you will see that it returns a tuple. 如果查看socket.recvfrom()文档 ,您会看到它返回一个元组。 If you only want the data portion, you're better off just calling socket.recv() . 如果只需要数据部分,最好只调用socket.recv()

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

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