Python服务器和Java客户端套接字

时间:2017-09-17 02:56:41

标签: java python

python中的服务器

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

我上面有一个python服务器和一个java客户端。 java客户端从用户获取输入并将其发送到python。这一切都运作良好。但是,python服务器正在接收来自java的字符串和附加空字符串。例如,从java客户端,当我发送单词" GET"时,python服务器能够接收到这个GET并打印" Yo,是什么?" 。然而,它可以追溯到"而真实"并且还会立即另外接收一个空字符串并开始用该空字符串检查条件。我试图修剪从java客户端收到的字符串。我怎么解决这个问题?谢谢。

2 个答案:

答案 0 :(得分:1)

conn.recv()返回尽可能多的数据(例如一个数据包)。另一方面,Java运行时库可以自由地将发送的数据细分为多个数据包。我猜它会发送一个带有“GET”的数据包和另一个带有最终换行的数据包。

解决方案是服务器等待并从流中收集输入,直到找到换行符完成命令。

答案 1 :(得分:1)

由于您在java程序中使用out.println(command),因此出现问题。它正在套接字上发送命令以及一些换行符。如果将其替换为out.print(command),则问题将得到解决。

println可能会在两个调用中内部发送主字符串和换行符,我不确定。但理想情况下,每个"命令"从客户端首先应该包括命令字符串的长度,然后是真正的命令。如果recv返回的值大于或小于所需的字节数,服务器端可能需要缓冲或拆分输入数据。

有一个小的python库datachunkpy可能有助于拆分和处理命令(https://pypi.python.org/pypi/datachunkpy/1.0.0