熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java UDP聊天程序

2013-11-23 18:55:25  來源: Java核心技術 

  import javaawtBorderLayout;

  import javaawtList;

  import javaawtTextField;

  import javaawteventActionEvent;

  import javaawteventActionListener;

  import javaioIOException;

  import DatagramPacket;

  import DatagramSocket;

  import InetAddress;

  import SocketException;

  import UnknownHostException;

  import javaxswingJFrame;

  import javaxswingJPanel;

  public class netchat {

  JFrame jf=new JFrame(我的網絡聊天程序);

  List l=new List();

  JPanel jp=new JPanel();

  TextField tip=new TextField();

  TextField tdata=new TextField();

  DatagramSocket ds;

  //DatagramPacket dp;

  public netchat()

  {

  tipsetText();

  try {

  ds=new DatagramSocket();

  } catch (SocketException e) {

  // TODO Autogenerated catch block

  eprintStackTrace();

  }

  new Thread(new Runnable()

  {

  DatagramPacket dp;

  public void run()

  {

  byte [] buf=new byte[];

  dp=new DatagramPacket(buf);

  //

  //    byte[] buf=new byte[];

  //    dp=new DatagramPacket(buf);

  while(true)

  {

  try {

  dsreceive(dp);

  //     ladd(dpgetAddress()getHostName()+say:+new String(bufdpgetLength()) );

  ladd(dpgetAddress()getHostAddress()+ say:+new String(buf+dpgetLength()) );

  } catch (IOException e) {

  // TODO Autogenerated catch block

  eprintStackTrace();

  }

  }

  }

  })start();

  }

  public static void main(String[] args) {

  // TODO Autogenerated method stub

  new netchat()init();

  }

  private void init()

  {

  jfadd(l);

  jpadd(tipBorderLayoutWEST);

  jpadd(tdataBorderLayoutEAST);

  jfadd(jpBorderLayoutSOUTH);

  jfsetSize( );

  jfsetVisible(true);

  jfsetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);

  tdataaddActionListener(new ActionListener()

  {

  public void actionPerformed(ActionEvent e)

  {

  //     byte[] buf;

  //     buf=egetActionCommand()getBytes();

  //     DatagramPacket dp;

  //     try

  //     {

  //      dp=new DatagramPacket(bufbuflengthInetAddressgetByName(tipgetText()));

  //      dssend(dp);

  //

  byte [] buf;

  buf=egetActionCommand()getBytes();

  DatagramPacket dp;

  try {

  dp= new DatagramPacket(bufbuflengthInetAddressgetByName(tipgetText()) );

  dssend(dp);

  } catch (UnknownHostException e) {

  // TODO Autogenerated catch block

  eprintStackTrace();

  } catch (IOException e) {

  // TODO Autogenerated catch block

  eprintStackTrace();

  }

  ((TextField)egetSource())setText();

  }

  });

  }

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/25988.html
  • 上一篇文章:

  • 下一篇文章:
  • 推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.