问题描述
我的目标是从python套接字向java套接字发送消息。我确实关注了上面提到的资源。但是我很难让Python客户端与Java服务器通信。主要是因为python中的(行尾)与java中的不同。
My aim is to send a message from python socket to java socket. I did look out on the resource mentioned above. However I am struggling to make the Python client talk to Java server. Mostly because (End of line) in python is different from that in java.
说我从python客户端写:消息1:abcd消息2:efgh消息3:q (退出)
say i write from python client: message 1: abcd message 2: efgh message 3: q (to quit)
在java服务器上:我收到消息1:abcdefghq后跟异常,因为python客户端已经从它的末尾关闭了套接字。
At java server: i receive message 1:abcdefghq followed by exception because the python client had closed the socket from its end.
有没有人可以为java和python之间的一致谈话提出解决方案。
Could anybody please suggest a solution for a consistent talk between java and python.
我使用的参考: http://www.prasannatech.net/2008/07/socket-programming-tutorial.html
更新:我忘了添加,我正在研究TCP。
Update: I forgot to add, I am working on TCP.
我的JAVA代码如下:(服务器套接字)
My JAVA code goes like this:(server socket)
String fromclient;
ServerSocket Server = new ServerSocket (5000);
System.out.println ("TCPServer Waiting for client on port 5000");
while(true)
{
Socket connected = Server.accept();
System.out.println( " THE CLIENT"+" "+ connected.getInetAddress() +":"+connected.getPort()+" IS CONNECTED ");
BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connected.getInputStream()));
while ( true )
{
fromclient = inFromClient.readLine();
if ( fromclient.equals("q") || fromclient.equals("Q") )
{
connected.close();
break;
}
else
{
System.out.println( "RECIEVED:" + fromclient );
}
}
}
我的PYTHON代码:(客户端套接字)
My PYTHON code : (Client Socket)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 5000))
while 1:
data = raw_input ( "SEND( TYPE q or Q to Quit):" )
if (data <> 'Q' and data <> 'q'):
client_socket.send(data)
else:
client_socket.send(data)
client_socket.close()
break;
OUTPUT ::
OUTPUT::
ON PYTHON CONSOLE (客户):
ON PYTHON CONSOLE(Client):
发送(Q型或Q退出):abcd(按ENTER)
SEND( TYPE q or Q to Quit):abcd ( pressing ENTER)
发送(TYPE q或Q to Quit):efgh(按ENTER键)
SEND( TYPE q or Q to Quit):efgh ( pressing ENTER)
发送(Q型或Q退出):q(按ENTER键)
SEND( TYPE q or Q to Quit):q ( pressing ENTER)
ON JAVA CONSOLE(服务器):
ON JAVA CONSOLE(Server):
TCPServer在端口5000上等待客户端
TCPServer Waiting for client on port 5000
客户/127.0.0.1:1335已连接
THE CLIENT /127.0.0.1:1335 IS CONNECTED
已收到:abcdefghq
RECIEVED:abcdefghq
推荐答案
您需要将 \ n
附加到数据结尾...
You need to append \n
to end of data...
ie :
client_socket.send(data + '\n')
这篇关于python客户端和java服务器之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!