基于: Server(Python) - Client(Java) communication using sockets
我只是想将Raspbian的RPI中的简单数据发送到运行Java客户端的Mac。
尽管如此,客户端日志始终停留在“尝试读取..”行中。 调试stdin似乎没有任何意义。 问题可能是发送数据的编码吗?
Python 2.7.133
Python服务器 (这里的区别在第18行,从原始代码中删除了对UTF-8的编码,以避免TypeError:str()最多使用1个参数(给定2个)-问题)
import socket
HOST = "192.168.0.38"
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
try:
s.bind((HOST, PORT))
except socket.error as err:
print('Bind failed. Error Code : ' .format(err))
s.listen(10)
print("Socket Listening")
conn, addr = s.accept()
while(True):
conn.send(bytes("Message")
print("Message sent")
data = conn.recv(1024)
print(data.decode(encoding='UTF-8'))
Java客户端
package com.example.demo;
//von https://stackoverflow.com/questions/31983000/serverpython-clientjava-communication-using-sockets
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Main {
static Thread sent;
static Thread receive;
static Socket socket;
public static void main(String args[]){
try {
socket = new Socket("192.168.0.38",9999);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
sent = new Thread(new Runnable() {
@Override
public void run() {
try {
BufferedReader stdIn =new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while(true){
System.out.println("Trying to read...");
String in = stdIn.readLine();
System.out.println(in);
out.print("Try"+"\r\n");
out.flush();
System.out.println("Message sent");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
sent.start();
try {
sent.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}