本帖最后由 NewDemo 于 2014-4-18 19:28 编辑
毕老师UDP聊天程序问题
1.输入886停不下来的原因应该是因为多线程的缘故,我是把break改成了System.exit(0),不知道大家是怎么处理的
2.想弄成图形界面的耍耍,刚开始就出错。。求指教
- package day23;
- import java.net.*;
- import java.io.*;
- import java.awt.*;
- import java.awt.event.*;
- public class Test4 {
- /*
- * UDP协议的聊天程序:收和发是分开的,所以将收发的动作分别封装到两个线程的run方法中即可 1.定义两个类send
- * rece分别实现Runnable,初始化时关联DatagramSocket 2.将收发动作分别封装到两个类的run方法中
- * 3.在主函数中开启两个线程
- */
- private Frame f;
- private TextArea ta1,ta2;
- private Button b;
- Test4(){
- method_0();
- }
- private void method_0(){
- Frame f = new Frame("对话");
- TextArea ta1 = new TextArea();
- TextArea ta2 = new TextArea();
- Button b = new Button("发送");
-
- f.setBounds(200,100,400,350);
- f.add(ta1);
- f.add(ta2);
- f.add(b);
- myEvent();
- f.setVisible(true);
-
- }
-
- private void myEvent(){
- f.addWindowListener(new WindowAdapter(){
- public void windowClosing(WindowEvent e){
- System.out.println("操作了窗体上的关闭");
- System.exit(0);
- }
- });
- }
-
-
- public static void main(String[] args) {
- // new Test4();这句话打开就报错,本来兴致满满想要做界面的,结果界面都出不来,想知道该怎么处理
- try{
- DatagramSocket dsend= new DatagramSocket();
- DatagramSocket drece= new DatagramSocket(10004);
- new Thread(new Send(dsend)).start();
- new Thread(new Rece(drece)).start();
- }
- catch(Exception e){
- throw new RuntimeException("监听端口失败");
- }
- }
- }
- class Send implements Runnable{
- private DatagramSocket ds;
- Send(DatagramSocket ds) {
- this.ds = ds;
- }
- public void run() {
- try {
- BufferedReader bufr = new BufferedReader(new InputStreamReader(
- System.in));//用到了缓冲区,为什么没有刷新操作,在哪里刷新??
- String line = null;
- while ((line = bufr.readLine()) != null) {
- if (line.equals("886"))
- break;//用break语句根本停不下来,
- // System.exit(0);
- byte[] buf = line.getBytes();
- DatagramPacket dp = new DatagramPacket(buf, buf.length,
- InetAddress.getByName("127.0.0.1"), 10003);// ?怎么写这个包收到的长度??
- System.out.println("我::"+line);
- ds.send(dp);
- }
- }
- catch (Exception e) {
- throw new RuntimeException("发送消息失败");
- }
- }
- }
- class Rece implements Runnable{
- private DatagramSocket ds;
- Rece(DatagramSocket ds) {
- this.ds = ds;
- }
- public void run() {
- try {
- while(true){
- byte[] buf = new byte[1024];
- DatagramPacket dp = new DatagramPacket(buf,buf.length);
- ds.receive(dp);
- String ip = dp.getAddress().getHostAddress();
- String data = new String(dp.getData(),0,dp.getLength());
- System.out.println(ip+"来自dos命令行:"+data);
- }
- }
- catch (Exception e) {
- throw new RuntimeException("接收消息失败");
- }
- }
- }
复制代码
|