java - Python 服务器没有从 Java 客户端接收到完整的字符串

标签 java python sockets tcp server

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

Java 代码发送:Hellooooooooo

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

最佳答案

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 是在您的程序崩溃时优雅地关闭套接字

关于java - Python 服务器没有从 Java 客户端接收到完整的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36422665/

相关文章:

java - 使用 JNDI 的 LDAP 用户密码认证

java - 将 awt/Cursor 转换为 JavaFX 场景/Cursor?

python - 凯拉斯, tensorflow : "TypeError: Cannot interpret feed_dict key as Tensor"

python - Pandas 将 DataFrame2 ROW append 到 DataFrame1 ROW

c++ - 在谈论重叠 I/O 时,上下文信息意味着什么?

c++ - 如何将图像转换为缓冲区,以便我可以使用套接字编程将其发送过来? C++

java - 当我将监听器传递给异步任务时出现类转换错误

java - 如何设置与按钮之间的间距不同的边距间隙?

python - 将对象序列化为Python代码而不是pickle

java 套接字问题