写了毕老师讲课的两个程序关于GUI和udp聊天程序的,但不知道怎样把它俩结合在一起,即形成一个图形化界面聊天工具!
代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
class Send implements Runnable{
private DatagramSocket ds;
public 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("886".equals(line))
break;
byte[] buf =line.getBytes();
DatagramPacket dp =
new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),10002);
ds.send(dp);
}}catch(Exception e){
throw new RuntimeException("发送端异常");
}
}
}
class Rece implements Runnable{
private DatagramSocket ds;
public Rece( DatagramSocket ds){
this.ds =ds;
}
public void run(){
while(true){
byte[] buf =new byte[1024];
DatagramPacket dp= new DatagramPacket(buf,buf.length);
try {
ds.receive(dp);
} catch (IOException e) {
throw new RuntimeException("接受端异常");
}
String ip = dp.getAddress().getHostAddress();
String data =new String(dp.getData(),0,dp.getLength());
int port=dp.getPort();
System.out.println(ip+": :"+data+": :"+port);
}
}
}
public class chatTest {
public static void main(String[] args) throws Exception{
DatagramSocket sendSocket= new DatagramSocket();
DatagramSocket receSocket= new DatagramSocket(10002);
new Thread(new Send(sendSocket)).start();
new Thread(new Rece(receSocket)).start();
}}
另一个关于界面的
import java.awt.*;
import java.awt.event.*;
class myWindow{
private Frame f;
private TextArea ta;
private TextField tf;
private Button b;
myWindow(){
init();
}
public void init(){
f= new Frame("my awt");
f.setSize(500,400);
f.setLocation(300,200);
f.setLayout(new FlowLayout());
ta=new TextArea(15, 50);
tf=new TextField(50);
b =new Button("发送");
f.add(ta);
f.add(tf);
f.add(b);
myEvent();
f.setVisible(true);
}
private void myEvent(){
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}});
//怎样在外面访问内部类的对象Text?例如不能在这里访问System.out.println(Text);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String text=tf.getText();
ta.setText(text);
tf.setText("");
}
});
}
public static void main(String[] args){
new myWindow();
}
}
我的思路是把聊天天程序的发送端和接收端都写入界面程序的内部类new ActionListener,可这样尝试了却没能成功
多线程怎么写入内部类呢,可能我思路错了吧!
希望大家在我代码的基础上合并改写一下;不胜感激!
最好写下你们的思想,控制台程序转化成图形界面的的技巧有吗。。
|