项目功能:
实现了多线程下的发送接收,比较好
希望可以加入GUI,类似聊天软件一样,有一个消息输入框,捕获输入消息,作为发送线程
有一个显示消息框,接收消息并显示,作为接收线程
不知道的是,当在线程中使用UI的gettext(),settext()时,是否子线程和UI线程冲突,赶紧学习下。
代码:
import java.net.*;
import java.io.*;
/*
编写一个聊天程序。
有收数据的部分,和发数据的部分。
这两部分需要同时执行。
那就需要用到多线程技术。
一个线程控制收,一个线程控制发。 因为收和发动作是不一致的,所以要定义两个run方法。
而且这两个方法要封装到不同的类中。 */
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){ byte[] buf =line.getBytes();
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.103"),10005); ds.send(dp);
//如果输入内容是"886",跳出循环
if("886".equals(line))
break;
} //4.关闭连接
ds.close(); }catch(Exception e){
throw new RuntimeException("发送端失败");
}
}
} class Recv implements Runnable
{
private DatagramSocket ds;
//构造方法
public Recv(DatagramSocket ds){
this.ds=ds;
} public void run() {
try{
while(true){
//2,创建数据包
byte[] buf =new byte[1024];
DatagramPacket dp =new DatagramPacket(buf,buf.length); //3,使用接收的方法将数据包存储到数据包中
ds.receive(dp);//阻塞式 //4.通过数据包对象的方法,解析其中的数据,比如端口,地址,内容等
String ip = dp.getAddress().getHostAddress();
int port = dp.getPort();
String content = new String(dp.getData(),0,dp.getLength());
System.out.println(ip+"::" +port+":"+content);
if(content.equals("886")){
System.out.println(ip+"有人退出..." );
break;
} }
//满足886跳出循环后,退出
ds.close();
}catch(Exception e){
throw new RuntimeException("接收端失败");
}
}
} public class ChatDemo
{
public static void main(String[] args) throws IOException{
DatagramSocket send =new DatagramSocket(); DatagramSocket recv =new DatagramSocket(10005); new Thread(new Send(send)).start();
new Thread(new Recv(recv)).start();
}
}
注意:Send、Recv类前面是不能加修饰符public的,否则会报错