我编写了以下代码:Python客户端发送String,JAVA服务器接收它,然后JAVA服务器发送String,Python客户端接收它。
但是我无法添加Python客户端发送String的代码行,而JAVA服务器又收到了它。
我使用BufferedReader来获取输入流,并使用readLine和utf-8对其进行读取。而且我使用PrintWriter获取输出流并发送字符串,但是当我在PrintWriter之后使用BufferedReader时,无法从python客户端获取String。
为什么使用PrintWriter发送String后,JAVA BufferedReader无法从python客户端接收String?
以下是我的代码。
JAVA服务器代码:
package solution;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class sol {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(8000);
Socket socket = server.accept();
BufferedReader br = new BufferedReader(
new InputStreamReader(
socket.getInputStream(), "UTF-8"
)
);
String a, b, c, d;
a = br.readLine();
b = br.readLine();
c = br.readLine();
System.out.println(a);
System.out.println(b);
System.out.println(c);
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
pw.print("Hello");
d = br.readLine(); // I can't receive? read? String from Python client..
System.out.println(d);
pw.close();
br.close();
socket.close();
server.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
Python客户端代码:
from socket import *
from select import select
HOST = '' // sorry it is my ip
PORT = 8000
client = socket()
try:
client.connect((HOST,PORT))
client.sendall(bytes("A\nB\nC\n", encoding = 'utf8'))
data = client.recv(1024)
data = data.decode()
print(data)
client.send(bytes("D\n", encoding = 'utf8'))
client.close()
except Exception as e:
print(e)