关闭任务管理器的 javaw 进程 可以 关闭之前 通过JAVA 编译 占用的端口
服务器端
package main; import java.net.*; import java.io.*; import java.awt.*; import java.awt.event.*; class M1 { public static void main(String[]a) { ChatGui c=new ChatGui(); } } //定义聊天窗口 class ChatGui { private Frame f; private TextArea t1; private TextArea t2; private Button b; private Thread th; ChatGui() { info(); } public void info() { reThread();//开启接收线程 } //线程 public void reThread() { try { DatagramSocket recS=new DatagramSocket(10326); new Thread(new Rce(recS)).start(); // DatagramSocket sendS=new DatagramSocket(); // new Thread(new Sen(sendS)).start(); } catch (Exception w) { throw new RuntimeException("创建线程失败"); } } class Rce implements Runnable { private DatagramSocket ds; Rce(DatagramSocket ds) { this.ds=ds; } public void run() { try { while(true) { byte[] b=new byte[1024*64]; DatagramPacket dp=new DatagramPacket(b,b.length); ds.receive(dp); String ip=dp.getAddress().getHostAddress(); String data=new String(dp.getData(),0,dp.getLength()); System.out.println(ip+"-----"+data); } } catch (Exception e) { throw new RuntimeException("接受失败"); } } } }
客户端
package main; import java.net.*; import java.io.*; import java.awt.*; import java.awt.event.*; class M2 { public static void main(String[]a) { ChatGui2 c=new ChatGui2(); } } //定义聊天窗口 class ChatGui2 { private Frame f; private TextArea t1; private TextArea t2; private Button b; private Thread th; ChatGui2() { info(); } public void info() { f=new Frame("聊天,不匹配的端口"); f.setBounds(300,100,500,600); f.setResizable(false); f.setLayout(new FlowLayout()); f.setVisible(true); t1=new TextArea("",20,60,TextArea.SCROLLBARS_VERTICAL_ONLY); t1.setEditable(false); t2=new TextArea("",5,50,TextArea.SCROLLBARS_VERTICAL_ONLY); b=new Button("发送"); f.add(t1); f.add(t2); f.add(b); myEvent(); } public void myEvent() { f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { seThread(); System.out.println(th.getName());//通过测试,这里每次点击发送按钮都会产生新的线程 } }); } //线程 public void seThread() {DatagramSocket sendS=null; System.out.println("xiancheng"); try { t1.append("我说:"+"\r\n"+t2.getText()+"\r\n"); if(sendS==null) sendS=new DatagramSocket(); th=new Thread(new Sen(sendS)); th.start(); System.out.println(th.isAlive()); } catch (Exception ew) { throw new RuntimeException("xiancheng失败"); } } class Sen implements Runnable { private DatagramSocket ds; Sen(DatagramSocket ds) { this.ds=ds; } public void run() { try { byte[] b=t2.getText().getBytes(); System.out.println(t2.getText()); System.out.println(b.length); DatagramPacket dp=new DatagramPacket(b,b.length,InetAddress.getByName("192.168.1.102"),60002); System.out.println(dp.getData()); ds.send(dp); t2.setText(""); } catch (Exception e) { throw new RuntimeException("发送失败"); } } } }