简体   繁体   English

如何通过python中的套接字将字符串发送到java服务器?

[英]How to send a string through a socket in python to a java server?

I have the following problem: I made a simple java server and a python client, but, since I am new to python I don't know how to send a string over the socket, so that the java server can read it the right way.我有以下问题:我做了一个简单的 java 服务器和一个 python 客户端,但是,由于我是 python 的新手,我不知道如何通过套接字发送一个字符串,以便 java 服务器可以以正确的方式读取它. This is some of the code of the client (written in Python 3.5).这是客户端的一些代码(用 Python 3.5 编写)。 The part with sock.send(b"1-4\\n") successfully did the job and I got from the server the expected message.带有 sock.send(b"1-4\\n") 的部分成功完成了这项工作,我从服务器获得了预期的消息。

...................
sock.connect((HOST, PORT))
sock.send(b"1-4\n")
data = sock.recv(102451223).decode()  
print(data) 
....................

But let's say that I want to get the input from the user and they only write "1-4".但是假设我想从用户那里获得输入,而他们只写“1-4”。 How to send the string input (I have input=("enter range:")) ?如何发送字符串输入(我有 input=("enter range:")) ? I tried with我试过

sock.send(b""+input+"\n") 

and it didn't work.它没有用。

Thank you!谢谢!

The problem is the way you encode your string: 问题是编码字符串的方式:

socket.send(("string1" + "string2").encode())

This should do the thing. 这应该做的事情。

Explanation : 说明

Your code only encodes the first part of the string, but you have to encode the complete text that should be sent to the server. 您的代码仅对字符串的第一部分进行编码,但是您必须对应发送到服务器的完整文本进行编码。

So guys, after some struggling for some time, I found a solution: 因此,经过一段时间的努力,我找到了解决方案:

 range_input =input(" Enter the ID-range")
 stringTosend = (str(range_input)+"\n")
 sock.connect((HOST, PORT))
 sock.send(stringTosend.encode())

I got the right information from the java server 我从Java服务器获得了正确的信息

s.connect((HOST, PORT))
z = input('to Server: ')
s.sendall(bytes(z, encoding='utf8'))#(sz.encode())#

this worked for me这对我有用

but in my case, my error is when typing z = input('to Server: ') , I must have a space at the end (before hitting the enter key), so string which I have just typed will show但就我而言,我的错误是在输入z = input('to Server: ') ,我必须在末尾有一个空格(在按回车键之前),所以我刚刚输入的字符串将显示

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

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