简体   繁体   English

TCP连接插座

[英]TCP connection socket

I wrote a simple TCP connection socket the server print the sentence from a client , but I got a wrong result anyone explain what is the problem, please. 我编写了一个简单的TCP连接套接字,服务器从客户端打印了该语句,但是如果有人解释了什么问题,我得到了错误的结果。

another question is what is the correct way to print the value of variable and sentence in python 3 另一个问题是在python 3中打印变量和句子的值的正确方法是什么

the server code is 服务器代码是

from socket import *


serverPort = 12000

serverSocket = socket(AF_INET, SOCK_STREAM)

serverSocket.bind(('', 12000))

serverSocket.listen(1)

connectionSocket, addr = serverSocket.accept()

while 1:
        sentence = connectionSocket.recv(10240)
        print ("from server", sentence)

serverSocket.close();

and client code is 客户代码是

from socket import *

serverName = '127.0.0.1'
serverPort = 12000

clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = input('Input lowercase sentense:') 
clientSocket.send(sentence.encode())
clientSocket.close()

the result is 结果是

enter image description here 在此处输入图片说明

you are getting that weird print because you are not checking data from client. 您得到的是奇怪的打印内容,因为您没有检查来自客户端的数据。 As a workaround you can check whether the data sent from client is empty or have value. 解决方法是,您可以检查从客户端发送的数据是否为空或有价值。 If it have value print it and otherwise don't do anything. 如果它有价值,请打印它,否则不做任何事情。

Please let me know if you need any code reference or something extra. 如果您需要任何代码参考或其他一些东西,请告诉我。

if sentense:
  print sentense

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

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