简体   繁体   English

python客户端与java服务器通信

[英]Communication between python client and java server

My aim is to send a message from python socket to java socket.我的目标是从 python 套接字发送消息到 java 套接字。 I did look out on the resource mentioned above.我确实看过上面提到的资源。 However I am struggling to make the Python client talk to Java server.但是,我正在努力让 Python 客户端与 Java 服务器通信。 Mostly because (End of line) in python is different from that in java.主要是因为 python 中的 (End of line) 与 java 中的不同。

say i write from python client: message 1: abcd message 2: efgh message 3: q (to quit)假设我从 python 客户端写信:消息 1:abcd 消息 2:efgh 消息 3:q(退出)

At java server: i receive message 1:abcdefghq followed by exception because the python client had closed the socket from its end.在 java 服务器:我收到消息 1:abcdefghq 后跟异常,因为 python 客户端已从其末端关闭套接字。

Could anybody please suggest a solution for a consistent talk between java and python.任何人都可以为 java 和 python 之间的一致对话提出解决方案。

Reference I used: http://www.prasannatech.net/2008/07/socket-programming-tutorial.html参考资料我用过: http://www.prasannatech.net/2008/07/socket-programming-tutorial.html

Update : I forgot to add, I am working on TCP.更新:我忘了补充,我正在研究 TCP。

My JAVA code goes like this:(server socket)我的 JAVA 代码是这样的:(服务器套接字)

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)我的 PYTHON 代码:(客户端套接字)

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(Client):在 PYTHON 控制台(客户端)上:

SEND( TYPE q or Q to Quit):abcd ( pressing ENTER) SEND(键入 q 或 Q 以退出):abcd(按 ENTER)

SEND( TYPE q or Q to Quit):efgh ( pressing ENTER) SEND(键入 q 或 Q 以退出):efgh(按 ENTER)

SEND( TYPE q or Q to Quit):q ( pressing ENTER) SEND(键入 q 或 Q 以退出):q(按 ENTER)

ON JAVA CONSOLE(Server):在 JAVA 控制台(服务器)上:

TCPServer Waiting for client on port 5000 TCPServer 在端口 5000 上等待客户端

THE CLIENT /127.0.0.1:1335 IS CONNECTED客户端 /127.0.0.1:1335 已连接

RECIEVED:abcdefghq收到:abcdefghq

\\n附加到data末尾:

client_socket.send(data + '\n')

ya..you need to add '\\n' at the end of the string in python client..... here's an example... PythonTCPCLient.py 你需要在python客户端的字符串末尾添加'\\ n'这里是一个例子...... PythonTCPCLient.py

` `

#!/usr/bin/env python

import socket

HOST = "localhost"
PORT = 8080

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))

sock.sendall("Hello\n")
data = sock.recv(1024)
print "1)", data

if ( data == "olleH\n" ):
    sock.sendall("Bye\n")
    data = sock.recv(1024)
    print "2)", data

    if (data == "eyB}\n"):
        sock.close()
        print "Socket closed"

` `

Now Here's the java Code: JavaServer.java ` 现在这是java代码: JavaServer.java`

 import java.io.*;
import java.net.*;

class JavaServer {
    public static void main(String args[]) throws Exception {
        String fromClient;
        String toClient;

        ServerSocket server = new ServerSocket(8080);
        System.out.println("wait for connection on port 8080");

        boolean run = true;
        while(run) {
            Socket client = server.accept();
            System.out.println("got connection on port 8080");
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter out = new PrintWriter(client.getOutputStream(),true);

            fromClient = in.readLine();
            System.out.println("received: " + fromClient);

            if(fromClient.equals("Hello")) {
                toClient = "olleH";
                System.out.println("send olleH");
                out.println(toClient);
                fromClient = in.readLine();
                System.out.println("received: " + fromClient);

                if(fromClient.equals("Bye")) {
                    toClient = "eyB";
                    System.out.println("send eyB");
                    out.println(toClient);
                    client.close();
                    run = false;
                    System.out.println("socket closed");
                }
            }
        }
        System.exit(0);
    }
}

` Reference: Python TCP Client & Java TCP Server `参考: Python TCP客户端和Java TCP服务器

here is a working code for the same: Jserver.java 这是一个相同的工作代码:Jserver.java

import java.io.*;
import java.net.*;
import java.util.*;
public class Jserver{
public static void main(String args[]) throws IOException{
    ServerSocket s=new ServerSocket(5000);

    try{
        Socket ss=s.accept();
        PrintWriter pw = new PrintWriter(ss.getOutputStream(),true);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedReader br1 = new BufferedReader(new InputStreamReader(ss.getInputStream()));
        //String str[20];
        //String msg[20];
        System.out.println("Client connected..");
        while(true)
        {
            System.out.println("Enter command:");
            pw.println(br.readLine());
            //System.out.println(br1.readLine());
        }
    }
    finally{}
    }
}

Client.py Client.py

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 5000                # Reserve a port for your service.

s.connect((host, port))
while 1:
    print s.recv(5000)
    s.send("message processed.."+'\n')

s.close 

I know it is late but specifically for your case I would recommend RabbitMQ RPC calls. 我知道它已经晚了但是特别针对你的情况我会推荐RabbitMQ RPC调用。 They have a lot of examples on their web in Python, Java and other languages: 他们在Web上有很多Python,Java和其他语言的例子:

在此输入图像描述

https://www.rabbitmq.com/tutorials/tutorial-six-java.html https://www.rabbitmq.com/tutorials/tutorial-six-java.html

for the people who are struggling with,对于正在挣扎的人来说,

data = raw_input ( "SEND( TYPE q or Q to Quit):" )

your can also use .encode() to send the data您还可以使用.encode()发送数据

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

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