在这里,我创建了一个充当客户端的 GUI。它包含一个文本字段和一个按钮。我的意图是打印用户在文本字段中键入的任何内容,必须在服务器命令提示符中显示。
服务器.java
import java.io.*;
import java.net.*;
public class Server {
Server(){
try{
ServerSocket server = new ServerSocket(4040);
while(true){
Socket sock = server.accept();
InputStream is = sock.getInputStream();
InputStreamReader streamReader = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(streamReader);
String string = reader.readLine();
System.out.println(string);
reader.close();
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
public static void main(String args[]){
new Server();
}
}
SimpleChatClientA.java
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import java.net.*;
import java.awt.*;
public class SimpleChatClientA {
JTextField outgoing;
PrintWriter writer;
Socket sock;
public void go(){
JFrame frame = new JFrame("chat client");
outgoing = new JTextField(20);
JButton sendButton = new JButton("send");
frame.add(outgoing);
frame.add(sendButton);
sendButton.addActionListener(new SendButtonListener());
frame.setLayout(new FlowLayout());
frame.setSize(500,100);
setUpNetworking();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void setUpNetworking(){
try {
Socket sock = new Socket("localhost",4040);
PrintWriter writer = new PrintWriter(sock.getOutputStream());
System.out.println("connection established");
} catch (Exception e) {
e.printStackTrace();
}
}
public class SendButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
try {
String str = outgoing.getText();
writer.println(str);
writer.flush();
}
catch (Exception ex) {
ex.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
public static void main(String args[]){
SimpleChatClientA simple = new SimpleChatClientA();
simple.go();
}
}
当我运行这个程序时。连接建立。但我看不到在服务器命令提示符的 JTextField 中输入的消息。我看到发生了一些错误。我不明白它是什么。我是java新手。请帮助我