连接python套接字和java套接字

时间:2014-01-03 21:59:25

标签: java python sockets

我一直在尝试在Java客户端套接字和Python服务器套接字之间发送一个简单的字符串。这是服务器套接字的代码:

HOST=''
PORT=12000
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADRR,1)
s.bind((HOST,PORT))
s.listen(5)
device=variador()
while True:

  conn,addr=s.accept()
  if data=="turn_on":
     respuesta=device.send_order(variador.start_order)
     conn.send(respuesta+'\n')
     conn.close()

,客户端代码为:

   try {

            Socket socket = new Socket("192.168.10.171", 12000);

            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

            BufferedReader in = new BufferedReader(new InputStreamReader(
                                       socket.getInputStream()));    

            BufferedReader stdIn = new BufferedReader(
                                          new InputStreamReader(System.in));

            out.print(command);

            out.close();
            in.close();
            socket.close();

        } catch (UnknownHostException e) {
            System.err.println("Unknown Host.");
           // System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for "
                               + "the connection.");
          //  System.exit(1);
        }

一切正常,直到我尝试读取服务器的响应,使用:

    String userInput;
  while ((userInput = stdIn.readLine()) != null) {
  out.println(userInput);
  System.out.println("echo: " + in.readLine());
  }

然后代码挂起,Python服务器没有收到任何信息,我用print测试了。

尝试先发送然后等待Java客户端服务器的响应是否有问题?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:6)

好吧,我发现java客户端挂起了,因为python服务器发送的消息没有用\ r \ n显式完成,所以python代码应该是这样的:

     HOST=''
     PORT=12000
     s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
     s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADRR,1)
     s.bind((HOST,PORT))
     s.listen(5)
     device=variador()
     while True:

       conn,addr=s.accept()
       if data=="turn_on\r\n":
        respuesta=device.send_order(variador.start_order)
        conn.send(respuesta+'\r\n')
       conn.close()

我知道从java,readline()和println中的方法名称来看应该是非常明显的,两者都表明java以序列结束字符串\ r \ n

答案 1 :(得分:0)


连接 Python 和 Java 套接字


安装包jpysocket

pip install jpysocket

https://pypi.org/project/jpysocket

导入库jpysocket

以下是一些示例

Python 服务器:

import jpysocket
import socket

host='localhost' #Host Name
port=12345    #Port Number
s=socket.socket() #Create Socket
s.bind((host,port)) #Bind Port And Host
s.listen(5) #Socket is Listening
print("Socket Is Listening....")
connection,address=s.accept() #Accept the Connection
print("Connected To ",address)
msgsend=jpysocket.jpyencode("Thank You For Connecting.") #Encript The Msg
connection.send(msgsend) #Send Msg
msgrecv=connection.recv(1024) #Recieve msg
msgrecv=jpysocket.jpydecode(msgrecv) #Decript msg
print("From Client: ",msgrecv)
s.close() #Close connection
print("Connection Closed.")

Java 客户端:

import java.io.*;  
  import java.net.*; 
  public class Client {
  public static void main(String[] args) {  
  try{      
  Socket soc=new Socket("localhost",12345);  
  DataOutputStream dout=new DataOutputStream(soc.getOutputStream());  
  DataInputStream in = new DataInputStream(soc.getInputStream());
  String msg=(String)in.readUTF();
  System.out.println("Server: "+msg);
  dout.writeUTF("Ok Boss");
  dout.flush();
  dout.close();
  soc.close();
  }
  catch(Exception e)
  {
      e.printStackTrace(); 
  }}}  

Python 客户端:

import jpysocket
import socket

host='localhost' #Host Name
port=12345    #Port Number
s=socket.socket() #Create Socket
s.connect((host,port)) #Connect to socket
print("Socket Is Connected....")
msgrecv=s.recv(1024) #Recieve msg
msgrecv=jpysocket.jpydecode(msgrecv) #Decript msg
print("From Server: ",msgrecv)
msgsend=jpysocket.jpyencode("Ok Boss.") #Encript The Msg
s.send(msgsend) #Send Msg
s.close() #Close connection
print("Connection Closed.")

Java 服务器:

import java.io.*;  
import java.net.*; 
public class Server {
  public static void main(String[] args) {
      try{ 
      ServerSocket serverSocket = new ServerSocket(12345);
      Socket soc = serverSocket.accept();
      System.out.println("Receive new connection: " + soc.getInetAddress());
      DataOutputStream dout=new DataOutputStream(soc.getOutputStream());  
      DataInputStream in = new DataInputStream(soc.getInputStream());
      dout.writeUTF("Thank You For Connecting.");
      String msg=(String)in.readUTF();
      System.out.println("Client: "+msg);
      dout.flush();
      dout.close();
      soc.close();
      }
      catch(Exception e)
      {
      e.printStackTrace(); 
  }
  }
  }