【发布时间】:2016-03-02 21:07:00
【问题描述】:
我花了一段时间阅读其他帖子,但似乎没有人和我有同样的情况。我已经尝试了所有我读过的解决方案,但没有结果,所以我决定提出这个问题。
我一直在开发服务器/客户端应用程序,客户端似乎没有从套接字读取数据,但服务器可以读取客户端发送的数据。客户端在尝试读取该行时冻结。这是我的代码:
客户:
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 修复,但都没有奏效!
-- 感谢您的阅读!
【问题讨论】:
-
无论您是否尝试过换行符和刷新,但它们都不起作用,您都应该使用它们(它们是必要的)。确保使用 PrintWriter(或任何基于文本的输出流)发送的每条消息都以 \n 结尾,并确保在发送每条消息后调用
flush。 -
+Nerdizzle 感谢您的回答!我已经尝试过了,但是没有用。我想既然我使用的是 println 而不是 print,它应该可以使用或不使用 \n,但以防万一,我尝试了它,但它仍然失败。我检查了,我正在使用 PrintWriter,我正在刷新(如上面的代码所示)
-
您的服务器可能会产生无限的数据流。除非服务器关闭连接,否则客户端中的
while (in.hasNext())永远不会终止。您可以用String ss = in.next();或if (in.hasNext())替换所有这些。您的客户正在接收数据,但过于贪婪 -
由于其中包含将其优先于其他问题的请求,因此我遗憾地投反对票。这里的读者大多是志愿者,他们会回答他们感兴趣的问题,而且他们会在闲暇时回答。 (否则你的问题是一个很好的问题)。
标签: java sockets networking network-programming server