亲们~~我来教你们在局域网下弄个“QQ”呵呵~~只需你的IP地址便可~~还等什么?
package com; import java.awt.*; import java.awt.event.*; import java.net.*; public class Chat{ Frame f=new Frame("我的聊天室"); TextField tfip=new TextField(15);//用户输入IP地址的文本框 List lst=new List(6);//用于显示接收消息的列表框 DatagramSocket ds; /** * @param args */ public Chat(){ try{ ds=new DatagramSocket(50005); }catch(SocketException e){ e.printStackTrace(); } new Thread(new Runnable(){ public void run(){ try{ byte buf[]=new byte[1024]; DatagramPacket dp=new DatagramPacket(buf,1024); ds.receive(dp); System.out.println("接收过来"); lst.add(new String(buf,0,dp.getLength())+" :from" +dp.getAddress().getHostAddress(),0); }catch(Exception e){ e.printStackTrace(); } } }).start(); } public static void main(String[] args) { Chat chat=new Chat(); chat.init(); } public void init(){ f.setSize(300, 300); f.add(lst); Panel p=new Panel(); p.setLayout(new BorderLayout()); p.add("West",tfip); TextField tfdata=new TextField(20); p.add("East",tfdata); f.add("South",p); f.setVisible(true); f.setResizable(false);//限制用户设置窗体的大小 f.addWindowListener(new WindowAdapter(){ public void WindowClosing(WindowEvent e){ f.setVisible(false); f.dispose(); System.exit(0); } }); tfdata.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ //有关网路发送信息的动作 byte[] buf=e.getActionCommand().getBytes(); try { DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName(tfip.getText()),50005); ds.send(dp); } catch(Exception e1){ e1.printStackTrace(); } ((TextField)e.getSource()).setText(""); } });//填写内容后,按下回车键所触发的事件 } }