您的位置:首页 > 其它

编写一个聊天程序:有接收数据部分,和发数据的部分, 这两部分需要同时执行,使用多线程实现,一个控制接收,一个控制发送

2016-03-23 12:31 961 查看
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;

/**

 * 编写一个聊天程序:有接收数据部分,和发数据的部分,

 * 这两部分需要同时执行,那就需要使用多线程

 * 一个控制接收,一个控制发送

 *

 */

public class ChartDemo {
public static void main(String[] args) {
try {
DatagramSocket sendSocket =new DatagramSocket();
DatagramSocket receSocket =new DatagramSocket(8888);
new Thread(new Send(sendSocket)).start();
new Thread(new Rece(sendSocket)).start();
} catch (SocketException e) {
e.printStackTrace();
}
}

}

//发送方法

class Send implements Runnable{

private DatagramSocket ds;
public Send(DatagramSocket ds) {
super();
this.ds = ds;

}
@Override
public void run() {
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in ));
String  line=null;
try {
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"),8888);
ds.send(dp);

}
} catch (IOException e) {
throw new RuntimeException("发送端失败");

}
}

}

//接收方法

class Rece implements Runnable{

private DatagramSocket ds;
public Rece (DatagramSocket ds) {
super();
this.ds = ds;

}
@Override
public void run() {
try {
while (true) {
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf, buf.length);
ds.receive(dp);
String ip=dp.getAddress().getHostAddress();
String data=new String(dp.getData(), 0, dp.getLength());
System.out.println(ip+"::::"+data);

}

} catch (Exception e) {
throw new RuntimeException("接收端失败");

}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: