【问题标题】:Python server does not receive complete string from java clientPython 服务器没有收到来自 java 客户端的完整字符串
【发布时间】:2016-07-25 04:13:19
【问题描述】:

我有一个 Python 服务器和一个 java 客户端。当一个字符串从 java 发送到 python 时,它是不完整的。示例:

Java 代码发送:Helloooooooooo

在 Python 中收到:

he

lloooooooo

oo

这里是代码

Python 服务器:

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_address = ("localhost", 10000)
print 'starting up on %s port %s' % server_address
sock.bind(server_address)

sock.listen(5)

while True:
     print 'waiting for a connection'
     connection, client_address = sock.accept()

     try:
         print 'connection from', client_address

         while True:
             data = connection.recv(1024)
             print 'received: ' + data
             print type(data)
             if data:
                 print 'sending data back to the client'
                 connection.sendall(data)
             else:
                 print 'no more data from', client_address
                 break

     finally:
         connection.close()

Java 客户端:

package server;

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

class Reciever_test {
 public static void main(String args[]) throws Exception {
        String sentence;
        String modifiedSentence;
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
    Socket clientSocket = new Socket("localhost", 10000);
    DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    while(true)
    {
        sentence = inFromUser.readLine();
        outToServer.writeBytes(sentence + "\n");
        modifiedSentence = inFromServer.readLine();
        System.out.println("FROM SERVER:" + modifiedSentence);
    }

    //clientSocket.close();
}

}

【问题讨论】:

  • 澄清一下,您是否希望 python 端一次打印整个字符串,而不是其中的一部分?
  • 是的,完全正确。我想要整个字符串,因为稍后我将使用它作为我将使用的操作的标识符
  • 然后你必须从套接字收集数据直到它完成,也许直到它包含\n
  • 是的,但我正在寻找是否有直接的解决方案。

标签: java python sockets tcp server


【解决方案1】:

正如 Klaus D. 所说的那样,recv 保证它最多会等待多少数据,它可能会决定在达到大小之前处理它所拥有的数据。我使用了一个简单的缓冲区,但我确信可能有更好的方法:

import socket
import atexit

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ("localhost", 10000)
print ('starting up on %s port %s' % server_address)
sock.bind(server_address)

sock.listen(5)

def close(connection):
    connection.close()

while True:
     print ('waiting for a connection')
     connection, client_address = sock.accept()
     atexit.register(close, connection)

     try:
         print ('connection from', client_address)

         buffer=[]
         while True:

             data = connection.recv(1024)
             for b in data:
                buffer.append(b)
             print ('received: ' + str(data))
             print (type(data))

             if str(buffer[-1]) == '\n': #if changed to use the buffer to decide when done receiving, the newline is the terminator
                 print ('sending data back to the client')
                 connection.sendall(''.join(buffer))
                 buffer = []
             # else:
             #     print ('no more data from', client_address)
             #     break

     finally:
         close(connection)

atexit 是在程序崩溃时优雅地关闭套接字

【讨论】:

    【解决方案2】:

    Java 客户端: 只是改变了我向服务器发送数据的方式。

     public static void main(String args[]) throws Exception {
        String sentence;
        String modifiedSentence;
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        Socket clientSocket = new Socket("localhost", 10000);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        Scanner sc = new Scanner(System.in);
        while(true)
        {
    
    
            while (true) {
                String input = sc.nextLine();
                out.print(input);
                out.flush();
                modifiedSentence = inFromServer.readLine();
                System.out.println("FROM SERVER:" + modifiedSentence);
            }
        }
    

    Python 服务器: 我的回复方式也必须改变(使用 send 而不是 sendall)

    while True:
    print 'waiting for a connection'
    connection, client_address = sock.accept()
    
    try:
        print 'connection from', client_address
    
        while True:
            data = connection.recv(4096)
            print data
            print type(data)
            if data:
                print 'sending data back to the client'
                connection.send(data + "\n")
            else:
                print 'no more data from', client_address
                break
    
    finally:
        connection.close()
    

    【讨论】:

      猜你喜欢
      • 2018-10-03
      • 2017-06-22
      • 1970-01-01
      • 2017-07-23
      • 2018-06-05
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      相关资源
      最近更新 更多