ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
简单服务器与客户端传输信息 Test4.java ~~~ package chat.a3; import javax.swing.*; import java.io.*; import java.net.*; import java.awt.event.*; public class Test4 extends JFrame implements ActionListener{ JTextArea jta =null;//文本域 JButton jb =null;//按钮 JTextField jtf=null;//文本框 JPanel jp =null;//标签 JScrollPane jsp=null;//滚动条 PrintWriter pw=null; public static void main(String[] args) { Test4 t = new Test4(); } public Test4(){ jta =new JTextArea(); jb =new JButton("发送"); jb.addActionListener(this); jtf =new JTextField(20); jp =new JPanel(); jp.add(jtf);jp.add(jb); jsp =new JScrollPane(jta); this.add(jsp);this.add(jp,"South"); this.setTitle("服务器端"); this.setSize(350,250); this.setLocation(300, 200); this.setResizable(false); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); try { ServerSocket ss=new ServerSocket(9999); Socket s=ss.accept();//接收服务器传过来的信息 InputStreamReader isr=new InputStreamReader(s.getInputStream()); BufferedReader br = new BufferedReader(isr); pw =new PrintWriter(s.getOutputStream(),true); while(true){ String xinxi=br.readLine(); jta.append("客户端对我说:"+xinxi+"\r\n"); } } catch (Exception e) { // TODO: handle exception } } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource()==jb){ String xinxi =jtf.getText(); jta.append("我对客户端说:"+xinxi+"\r\n"); pw.println(xinxi); jtf.setText("");//清空文本框 } } } ~~~ Test5.java ~~~ package chat.a3; import javax.swing.*; import java.io.*; import java.net.*; import java.awt.event.*; public class Test5 extends JFrame implements ActionListener{ JTextArea jta =null;//文本域 JButton jb =null;//按钮 JTextField jtf=null;//文本框 JPanel jp =null;//标签 JScrollPane jsp=null;//滚动条 PrintWriter pw=null; public static void main(String[] args) { Test5 t = new Test5(); } public Test5(){ jta =new JTextArea(); jb =new JButton("发送"); jb.addActionListener(this); jtf =new JTextField(20); jp =new JPanel(); jp.add(jtf);jp.add(jb); jsp =new JScrollPane(jta); this.add(jsp,"Center");this.add(jp,"South"); this.setTitle("客户端"); this.setSize(350,250); this.setLocation(300, 200); this.setResizable(false); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); try { Socket s=new Socket("127.0.0.1",9999); InputStreamReader isr=new InputStreamReader(s.getInputStream()); BufferedReader br = new BufferedReader(isr); pw =new PrintWriter(s.getOutputStream(),true); while(true){ String xinxi=br.readLine(); jta.append("服务器对我说:"+xinxi+"\r\n"); } } catch (Exception e) { // TODO: handle exception } } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource()==jb){ String xinxi =jtf.getText(); jta.append("我对服务器说:"+xinxi+"\r\n"); pw.println(xinxi); jtf.setText("");//清空文本框 } } } ~~~ 先启动服务器Test.java,再启动客户端Test1.java 结果: ![](https://box.kancloud.cn/67e1aa52e95bc834544cae0d28fde9eb_764x283.png)