【发布时间】:2015-03-09 21:48:38
【问题描述】:
您好,我需要一些关于我用 Java 编写的服务器/客户端套接字程序的快速帮助。在客户端输入标准输入时,一切都按预期工作。服务器每次都以正确的数据响应。但是当我使用 actionListener 将数据发送到服务器时,没有返回任何内容。数据正在由服务器发送和读取,可以在服务器端打印,只是不会返回给客户端。
所以这一定是从 actionListener 发送的数据格式或类型的问题(不幸的是,我对流的了解不够),还是服务器端的流有问题?
非常感谢任何帮助!
public class Serv {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8889);
System.out.println("Waiting for client...");
} catch (IOException e) {
System.err.println("Could not listen on port: 8889.");
System.exit(1);
}
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine, outputLine;
Protocol p = new Protocol();
out.println("welcome");
while ((inputLine = in.readLine()) != null) {
outputLine = p.processInput(inputLine);
System.out.println("Input: "+inputLine + "\nOutput: "+outputLine);
out.println(outputLine);
if (outputLine.equals("Exit")) { break; }
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
public class Cl extends JFrame {
public static PrintWriter out = null;
public static String fromUser;
public static void Client() {
saveAnswer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonModel b = group.getSelection();
if (b.getActionCommand() == "A") { sendAnswer = radioA.getText(); }
if (b.getActionCommand() == "B") { sendAnswer = radioB.getText(); }
if (b.getActionCommand() == "C") { sendAnswer = radioC.getText(); }
String data = "÷" + sendAnswer;
out.println(data);
}
});
}
public static void main(String[] args) throws IOException {
Socket Socket = null;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
boolean checkOpen = false;
Socket clientS = new Socket("localhost", 8889);
out = new PrintWriter(clientS.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientS.getInputStream()));
String fromServer;
while ((fromServer = in.readLine()) != null) {
if (fromServer.startsWith("®")) {
if (checkOpen == false) { Cl.Client(); checkOpen = true; }
qA.splitter(fromServer);
}
if (fromServer.equals("Exit")) { break; }
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
else { System.out.println("trouble"); }
}
out.close();
in.close();
stdIn.close();
Socket.close();
}
}
【问题讨论】:
-
对不起,我忘了补充,我删除了所有非必要数据,因为我 99% 确定我已将问题缩小到此代码中的某些内容。如果有帮助,我可以发布整个内容!
-
格式不正确的代码通常是人们不会阅读的代码。考虑尝试发布格式良好的可读代码。最好能创建并发布mcve。
-
你为什么在 Swing 程序中从标准输入读取数据?
标签: java sockets client server jradiobutton