javasocket服务器,我没有收到服务器发送的消息
我有一个客户机-服务器连接
当我的服务器连接到客户机时,它必须通过outputstream发送消息,然后在从inputStream接收消息时打印消息。但是,当客户端连接时,我会收到“已连接”消息,但没有看到服务器发送的“这是一条文本消息”
这是我的服务器:
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);
}
}
);
}
}
这就是我得到的回报:
# 1 楼答案
你的
input.readLine()
在你的服务器端客户端输入流上。这意味着它试图从客户那里读取收入信息如果您不想阅读服务器从客户端发送给客户端的消息(我认为您想要的,但我可能误解了)。您必须获得客户端套接字输入流。 你可能在某处打过电话的插座:
Socket clientSocket = new Socket("localhost", 7100);