无法从Python套接字到Java套接字接收字符串数据

时间:2018-07-29 03:26:21

标签: java python sockets

我在使用套接字时遇到麻烦

如您所见,当我尝试将字符串从JAVA发送到PYTHON时,代码会起作用。

但是,当我尝试将字符串从PYTHON发送到JAVA时遇到了麻烦,这是相反的方式。而且我需要将其转换为字节并对其进行解码,因为在发送完该字符串之前我已经对其进行了编码。

因此,现在的问题是,当我从Python套接字发送一个字符串并通过Java套接字接收该字符串时,我的代码有何错误?

我真的需要帮助,谢谢!

Python(服务器)代码:

import socket
import ssl
import hashlib
import os
from Crypto.Cipher import AES
import hashlib
from Crypto import Random 

sHost = ''
sPort = 1234


def bindSocket():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #IPv4 and TCP
    try:
        s.bind((sHost,sPort))
        print("Socket created and binded")
    except socket.error as msgError:
        print(msgError)
        print("Error in Binding Socket")
    return s #so that we can use it


def socketConnect():
    s.listen(1) #listen to 1 connection at a time


    while True:
        try:
            conn, address = s.accept() #Accept connection from client
            print ("Connected to: " + address[0] + ":" +str(address[1]))
        except socket.error as error:
            print ("Error: {0}" .format(e))
            print ("Unable to start socket")
        return conn






def loopCommand(conn):
    while True:
        passphrase = "Hello Java Client "
        data = conn.recv(1024)#receive the message sent by client

        print(data)

        conn.send(passphrase.encode('utf-8'))

        print("Another String is sent to Java")

s = bindSocket()

while True:
    try:
        conn = socketConnect()
        loopCommand(conn)
    except:
        pass

Java(客户端)代码:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketSTesting {

    public Socket socketStartConnect() throws UnknownHostException, IOException {
        String ip = "192.168.1.16";
        int port = 1234;
        Socket clientSocket = new Socket(ip, port);
        if (clientSocket.isConnected()) {
            System.out.println("It is connected to the server which is " + clientSocket.getInetAddress());

        } else if (clientSocket.isClosed()) {
            System.out.println("Connection Failed");
        }
        return clientSocket;
    }

    public void sendString(String str) throws Exception {

        // Get the socket's output stream
        Socket socket = socketStartConnect();
        OutputStream socketOutput = socket.getOutputStream();

        byte[] strBytes = str.getBytes();



        // total byte
        byte[] totalByteCombine = new byte[strBytes.length];
        System.arraycopy(strBytes, 0, totalByteCombine, 0, strBytes.length);

        //Send to Python Server
        socketOutput.write(totalByteCombine, 0, totalByteCombine.length);
        System.out.println("Content sent successfully");


        //Receieve Python string
        InputStream socketInput = socket.getInputStream();
        String messagetype = socketOutput.toString();
        System.out.println(messagetype);

    }

    public static void main(String[] args) throws Exception {

        SocketSTesting client = new SocketSTesting();

        String str = "Hello Python Server!";
        client.sendString(str);


    }

}

1 个答案:

答案 0 :(得分:1)

您似乎认为String messagetype = socketOutput.toString();执行I / O。它不会,所以打印它甚至调用它不会执行任何操作,也不会证明任何操作。您需要从套接字 input 流中读取

BTW clientSocket.isConnected()在测试时不能为假。如果连接失败,则将引发异常。同样,clientSocket.isClosed()在测试时可能不正确,因为尚未关闭刚刚创建的套接字。此外,如果isClosed()为true,则并不意味着“连接失败”,而isConnected()为false并不意味着isClosed()为true。删除所有这些。