2017-09-17 41 views
0

服務器在PythonPython的服務器和Java客戶端插座

import socket 
from sys import getsizeof 

host = '' 
port = 5560 

storedValue = "Yo, what's up?" 

def setupServer(): 
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    print("Socket created.") 
    try: 
     s.bind((host, port)) 
    except socket.error as msg: 
     print(msg) 
    print("Socket bind comPlete.") 
    return s 

def setupConnection(): 
    s.listen(1) # Allows one connection at a time. 
    print("Waiting for client") 
    conn, address = s.accept() 
    return conn 

def GET(): 
    reply = storedValue 
    return reply 

def REPEAT(dataMessage): 
    reply = dataMessage[1] 
    return reply 

def dataTransfer(conn, s): 
    # A big loop that sends/receives data until told not to. 
    while True: 
     # Receive the data 
     data = conn.recv(1028) # receive the data 
     data = data.decode('utf-8') 
     data = data.strip() 
     print("data value from client: " + data) 
     # Split the data such that you separate the command 
     # from the rest of the data. 
     command = str(data) 
     print("data length from client: " + command) 
     reply = "" 
     if command == "GET": 
      reply = GET() 
      print (command) 
      print (reply) 
     elif command == 'REPEAT': 
      reply = REPEAT(dataMessage) 
     elif command == 'EXIT': 
      print("Our client has left us :(") 
      break 
     elif command == 'KILL': 
      print("Our server is shutting down.") 
      s.close() 
      break 
     else: 
      reply = 'Unknown Command' 
     # Send the reply back to the client 
     conn.sendall(bytes(reply, 'utf-8')) 
     print("Data has been sent!") 
    conn.close() 

s = setupServer() 

while True: 
    try: 
     conn = setupConnection() 
     dataTransfer(conn, s) 
    except: 
     break 

客戶端在Java

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

public class pcClient { 

    public static void main(String[] args) { 

     Socket rpiSocket = null; 
     DataInputStream in = null; 
     PrintStream out = null; 

     try { 
      rpiSocket = new Socket("localhost",5560); 
      out = new PrintStream(rpiSocket.getOutputStream()); 
      in = new DataInputStream(new BufferedInputStream(rpiSocket.getInputStream())); 
     } catch (UnknownHostException e) { 
      System.err.println("Don't know about host: hostname"); 
     } catch (IOException e) { 
      System.err.println("Couldn't get I/O for the connection to: hostname"); 
     } 

     try { 
     if (rpiSocket != null && out != null && in != null) { 
      while(true) { 
       System.out.println("Please input your command "); 
       Scanner scanner = new Scanner(System.in); 
       String command = scanner.nextLine(); 

       if(command.equals("KILL")) { 
        break; 
       } 

       System.out.println("Sending command to client: " + command); 
       out.println(command); 

       byte[] bytes = new byte[1024]; 

       in.read(bytes); 
       String reply = new String(bytes, "UTF-8"); 
       System.out.println("Reply from server: " + reply.trim()); 
      } 
     } 

      rpiSocket.close(); 
      System.out.println("Connections closed successfully"); 
     } 
     catch (IOException e) { 
      System.err.println("IOException: " + e); 
     } 
    } 
} 

我上面的蟒蛇服務器和Java客戶端。 Java客戶端從用戶處獲取輸入並將其發送給python。所有這一切運作良好。但是,python服務器正在接收來自java的字符串和附加的空字符串。例如,從java客戶端,當我發送單詞「GET」時,python服務器能夠接收到這個GET並打印出「喲,怎麼了?」。但是,它返回到「While True」並立即另外收到一個空字符串,並開始檢查該空字符串的條件。我試圖修剪從java客戶端收到的字符串。我該如何解決這個問題?謝謝。

回答

0

由於您使用的是java程序out.println(command),因此出現了問題。它正在發送命令並在套接字上發送一些換行符。如果用out.print(command)代替它,問題將得到解決。

println可能在兩次調用中內部發送主字符串和換行符,我不確定。但理想情況下,客戶端的每個「命令」應首先包含命令字符串的長度,然後是真實命令。如果recv返回大於或小於所需的字節數,服務器端可能需要緩衝或分割輸入數據。

有一個小型的python庫datachunkpy可以幫助分割和處理命令(https://pypi.python.org/pypi/datachunkpy/1.0.0

0

conn.recv()返回與立即可用的數據(例如一個數據包)相同的數據。另一方面,Java運行時庫可以自由地將發送的數據細分爲多個數據包。我想它會發送一個帶有「GET」的數據包和另一個帶有最終換行符的數據包。

解決方案是讓服務器等待並從流中收集輸入,直到找到換行符來完成命令。