【发布时间】:2014-05-27 20:51:32
【问题描述】:
我有一个客户端-服务器连接..
当我的服务器连接到客户端时,它必须通过输出流发送一条消息,然后在从输入流接收到消息时打印它。但是当客户端连接时,我收到“已连接”消息,但我没有看到“这是一条短信\n”发送给我的服务器
这是我的服务器:
public class Server1 extends JFrame{
static JTextArea testoarea;
static Socket socket;
static ServerSocket server;
public Server1(){
testoarea = new JTextArea();
add(new JScrollPane(testoarea));
setSize(600, 700);
setVisible(true);
}
public static void main(String[] args) {
Server1 server1 = new Server1();
server1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
inizzializza();
connetti();
}
private static void inizzializza(){
try {
server = new ServerSocket(7100);
showMessage("Server Iniziato\n");
} catch (IOException e) {
System.out.println(e);
}
}
private static void connetti() {
try {
socket = server.accept();
showMessage("Connected \n");
PrintWriter output = new PrintWriter(socket.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output.println("this is a Test message\n");
showMessage(input.readLine().toString());
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void showMessage(final String text) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
testoarea.append(text);
}
}
);
}
}
这是我回来的:
【问题讨论】:
-
下次请尽量不要从编辑器中复制/粘贴文本,因为stackoverflow代码中的一个制表符实际上等于四个空格。
-
@Theolodis 哦对不起,我不知道..
-
没问题,我帮你修好了。
-
哦,问题可能是你收到消息后正在刷新,但我猜你只有刷新请求才能得到答案。 TL;DR:
output.println("this is a Test message\n"); output.flush();解决了您的问题。 -
两点说明:您当然不想在
output.println()通话中添加“\n”。其次,如果你想调用output.flush(),你想在input.readLine()之前调用它