服务端用java还是python,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.

say i write from python client: message 1: abcd message 2: efgh message 3: q (to quit)

At java server: i receive message 1:abcdefghq followed by exception because the python client had closed the socket from its end.

Could anybody please suggest a solution for a consistent talk between java and python.

Update: I forgot to add, I am working on TCP.

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 );

}

}

}

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::

ON PYTHON CONSOLE(Client):

SEND( TYPE q or Q to Quit):abcd ( pressing ENTER)

SEND( TYPE q or Q to Quit):efgh ( pressing ENTER)

SEND( TYPE q or Q to Quit):q ( pressing ENTER)

ON JAVA CONSOLE(Server):

TCPServer Waiting for client on port 5000

THE CLIENT /127.0.0.1:1335 IS CONNECTED

RECIEVED:abcdefghq

解决方案

You need to append \n to end of data...

i.e. :

client_socket.send(data + '\n')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值