java吧 关注:1,236,515贴子:12,707,554
  • 0回复贴,共1
代码如下:
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
class Send implements Runnable
{
private DatagramSocket ds;
private static String s;
Send(DatagramSocket ds)
{
this.ds=ds;
}
public static void give(String string)
{
s=string;
}
public void run()
{
try
{
if(s!=null)
{
BufferedReader br = new BufferedReader(new StringReader(s));
String str = null;
while((str=br.readLine())!=null)
{
byte [] arr = str.getBytes();
DatagramPacket dp = new DatagramPacket(arr,arr.length,
InetAddress.getByName("192.168.1.255"),10003);
ds.send(dp);
}
}
}
catch(Exception e)
{
throw new RuntimeException("发送数据失败");
}
}
}
class Dece implements Runnable
{
private Frame f;
private Button b;
private TextArea ta,tas;
private DatagramSocket ds;
Dece(DatagramSocket ds)
{
this.ds=ds;
info();
}
public void info()
{
f = new Frame("聊天");
b= new Button("发送");
ta = new TextArea(7,70);
tas = new TextArea(27,85);
f.setLayout(new FlowLayout());
f.setBounds(300,200,650,600);
f.add(tas);
f.add(ta);
f.add(b);
myevent();
f.setResizable(false);
f.setVisible(true);
}
public void myevent()
{
tas.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
e.consume();
}
});
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String s = ta.getText();
Send.give(s);
ta.setText("");
}
});
}
public void run()
{
try
{
while(true)
{
byte [] arr = new byte [1024];
DatagramPacket dp = new DatagramPacket(arr,arr.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
tas.append(ip+":"+data+"\r\n");
}
}
catch(Exception e)
{
throw new RuntimeException("接收数据失败");
}
}
}
class Trydemo
{
public static void main (String [] args)
{
try
{
DatagramSocket ds1 = new DatagramSocket();
DatagramSocket ds2 = new DatagramSocket(10003);
new Thread(new Send(ds1)).start();
new Thread(new Dece(ds2)).start();
}
catch(Exception e)
{
throw new RuntimeException("抛异常啦");
}
}
}
问题:输入文字后点发送上面的文本框没显示


IP属地:广东1楼2015-01-19 14:33回复