我花了一段时间阅读其他帖子,似乎没有人和我有同样的情况。我已经尝试了所有我没有读过的解决方案,所以我决定创建这个问题。
我一直在研究服务器/客户端应用程序,而客户端似乎没有从套接字读取数据,但服务器可以读取客户端发送的数据。客户端在尝试读取线路时冻结。这是我的代码:
客户端:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
public class Main {
public static Socket s = connect();
public static void sendMessage(String msg) {
if (s != null) {
PrintWriter outWriter = null;
try {
outWriter = new PrintWriter(s.getOutputStream(), true);
outWriter.println(msg);
outWriter.flush();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
outWriter.close();
} finally {
}
} else {
System.err.println("Error, socket is null!");
}
}
public static String readMessage() {
if (s != null) {
Scanner in = null;
try {
in = new Scanner(s.getInputStream());
} catch (IOException ex) {
ex.printStackTrace();
}
String ss = "";
while (in.hasNext()) {
ss += in.next();
}
System.out.println("REPONSE:" + ss);
return ss;
} else {
System.err.println("Error, socket is null!");
}
return "err/readMessage";
}
public static Socket connect() {
try {
Socket sss = new Socket("localhost", 25586);
sss.setKeepAlive(true);
return sss;
} catch (IOException ex) {
ex.printStackTrace();
System.exit(-1);
}
return null;
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
sendMessage("HELO");
System.out.println("Thread initialized.");
while (true) {
try {
System.out.println("Awaiting message...");
Thread.sleep(100);
String messages = readMessage();
System.out.println("Message recieved! '" + messages + "'");
String[] message = messages.split("/");
System.out.println(messages);
if (message[0].equalsIgnoreCase("DERP")) { // err/reason
System.out.println("IT'S FINALLY WORKING!");
} else {
System.out.println("Didn't work :( response:" + messages);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
});
t.start();
}
});
}
}
服务器
import java.util.List;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main { /* SERVER */
public static List<EchoThread> list = new ArrayList<>();
public static int PORT = 25586;
public static void main(String[] args) throws IOException {
new Main(PORT);
}
public Main(int port) throws IOException {
this.PORT = port;
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new threa for a client
EchoThread s = new EchoThread(socket);
s.start();
list.add(s);
}
}
public static void sendMessageToAll(String ss) {
for (EchoThread s : list) {
s.allMessage(ss);
}
}
}
class EchoThread extends Thread {
protected Socket socket;
InputStream inp = null;
BufferedReader brinp = null;
public EchoThread(Socket clientSocket) {
this.socket = clientSocket;
try {
inp = socket.getInputStream();
brinp = new BufferedReader(new InputStreamReader(inp));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
String line;
while (true) {
try {
line = brinp.readLine();
if ((line == null) || line.equalsIgnoreCase("EXIT")) {
socket.close();
return;
} else {
handle(line);
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
public void handle(String s) {
String[] keys = s.split("/");
System.out.println("random: Handling request\"" + s + "\"");
System.out.println("Response: DERP");
if (s.equalsIgnoreCase("HELO")) {
System.out.println("Message recieved:" + s);
}
respond("DERP");
}
public void respond(String s) {
try {
System.out.println("Response_WILLBE:" + s);
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
pw.println(s);
pw.flush();
System.out.println("Message sent!");
} catch (Exception ex) {
Logger.getLogger(EchoThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void allMessage(String s) {
respond(s);
}
}
我尝试了flush()
代码以及\r\n
和println
修复,但都没有效果!
- 谢谢你的阅读!
答案 0 :(得分:3)
我对客户端和服务器通信方式之间的差异非常好奇。例如,客户端使用Scanner
来读取输入,而服务器使用BufferedReader
(这是我个人的偏好)。只是一个建议:保持一致。
现在 - 首先,客户端只发送一条消息,然后在无限循环中开始无限期地读取。看到你确切地知道服务器在向它发送“HELO”之后应该如何响应(它应该响应一行“DERP”),没有理由在任何类型的循环中从服务器读取。
服务器上存在同样的问题。由于客户端现在是,它总是只向服务器发送一行(“HELO”)。因此,服务器应该只期望一行,只读一行。绝对没有理由在循环中读取输入。但是,实际问题仅存在于客户端的代码中:
您目前有while(in.hasNext())
条件是客户端从服务器读取输入的时间。 The hasNext method differs in logical function depending on the method of communication.在套接字通信的情况下,hasNext
期望一个流,因此,除非套接字被关闭,否则它将始终返回true。
除非您不知道要读取多少行,否则请避免在套接字通信中使用循环。在这种情况下,您应首先让发送方向接收方发送某种号码,然后接收方应读取for循环读取'n'次的后续行(其中n是接收的号码)。< / p>
以下是使用PrintWriters
和BufferedReaders.
<强>客户端强>
public static void main(String[] args){
try{
Socket socket = new Socket("localhost", 12345);
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.write("HELO\n"); //print("HELO\n") and println("HELO") should work too.
out.flush();
System.out.println("Server says " + in.readLine());
in.close();
out.close();
socket.close();
}catch(IOException e){e.printStackTrace();}
}
服务器强>
public static void main(String[] args){
try{
ServerSocket serverSocket = new ServerSocket(12345);
while(true){
new Thread(new ClientConnectionThread(serverSocket.accept())).start();
}
}catch(IOException e){e.printStackTrace();}
}
private class ClientConnectionThread implements Runnable{
private Socket socket;
public ClientConnectionThread(Socket socket){
this.socket = socket;
}
@Override
public void run(){
try{
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
System.out.println("Client says " + in.readLine());
out.write("HELO Back!\n"); //again, print("HELO Back!\n") and
//println("HELO Back!") should also work
out.flush();
out.close();
in.close();
socket.close();
}catch(IOException e){e.printStackTrace();}
}
}
请注意,实际通信中不需要循环。
答案 1 :(得分:1)
正如@zapl评论的那样,当您从服务器读取数据时,您的客户端非常贪婪。让我们看看用于从服务器读取数据的过程:
String ss = "";
while (in.hasNext()) {
ss += in.next();
}
System.out.println("REPONSE:" + ss);
此代码将不断从服务器提取数据,直到关闭流。从文件中读取数据或解析一个非常适合这些情况的字符串时,您可能会使用这种类型的代码块,因为您希望流中的所有数据都成为您的字符串。
您要查看的是从新行\n
指定的服务器中读取第一个resposne。您应该只检查是否while(in.hasNext())
而不是in.hasNext()
,如果是,那么请将其作为回复。
String ss = "";
if (in.hasNext()) {
ss += in.next();
}
System.out.println("REPONSE:" + ss);
或者更优雅
if (in.hasNext()) {
String response = in.next();
System.out.println("REPONSE:" + response);
return response;
}
....
答案 2 :(得分:1)
首先,对于套接字,我总是喜欢运行服务器并通过localhost telnet到它。当我和你一起做的时候,我来回都没有问题。所以现在只需要修理你的客户。
对于客户端,摆脱(暂时)您对Scanner类的使用。这个类有另外一组可能导致问题的用法。相反,保持简单。
将您的客户端更改为使用BufferedReader。这是你的新readMessage()方法:
public String readMessage() {
if (s != null) {
BufferedReader in = null;
try {
System.out.println("Creating reader");
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
} catch (IOException ex) {
}
String ss = "";
try {
ss = in.readLine();
} catch (IOException e) {
}
System.out.println("REPONSE:" + ss);
return ss;
您的客户端现在可以正常工作(它适用于我),这意味着您在使用扫描仪时遇到问题。
我会让你去调试,因为那不是你的问题所在。玩得开心! ;)