Невозможно получить строковые данные из сокета Python в сокет JavaJAVA

Программисты JAVA общаются здесь
Anonymous
 Невозможно получить строковые данные из сокета Python в сокет Java

Сообщение Anonymous »

У меня проблемы с использованием сокетов. Как видите, код сработал, когда я пытался отправить строку из Java на Python. противоположный путь. Мне нужно, чтобы он конвертировал в байты и декодировал ее, поскольку я закодировал строку, прежде чем отправить ее. < /P>
Проблем От сокета Python и получения строки от Java Socket?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
< /code>
java (клиент) код: < /p>
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");

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


Подробнее здесь: https://stackoverflow.com/questions/515 ... ava-socket

Вернуться в «JAVA»