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

时间:2016-04-05 09:42:43

标签: java python sockets tcp server

我有一个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();
}

}

2 个答案:

答案 0 :(得分:0)

Klaus D.s所说的无用, 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 是在程序崩溃的情况下优雅地关闭套接字

答案 1 :(得分:0)

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()