UDP通信基础(聊天室)
//主函数
package chat;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Chartdemo {
/**
* @param args
*/
public static void main(String[] args) {
try {
DatagramSocket send=new DatagramSocket();
/*
* 接收数据必须要有一个端口
*/
DatagramSocket recive=new DatagramSocket(10001);
new Thread(new Send(send)).start();
new Thread(new Recive(recive)).start();
} catch (SocketException e) {
e.printStackTrace();
}
}
}
//发送端
package chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Send implements Runnable {
DatagramSocket socket = null;
public Send(DatagramSocket socket) {
this.socket = socket;
}
@Override
public void run() {
BufferedReader in = null;
try {
/*
* 从键盘读取数据
*/
in = new BufferedReader(new InputStreamReader(System.in));
String string = null;
byte[] buf = null;
while ((string = in.readLine()) != null) {
buf = string.getBytes();
/*
* 广播发送数据
*/
DatagramPacket dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName("192.168.1.255"), 10001);
socket.send(dp);
/*
* 退出聊天
*/
if("886".equals(string))
{
break;
}
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//接收端
package chat;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Recive implements Runnable {
DatagramSocket socket = null;
public Recive(DatagramSocket socket) {
this.socket = socket;
}
@Override
public void run() {
DatagramPacket dp=null;
try {
while(true)
{
byte[]buf=new byte[1024];
dp=new DatagramPacket(buf, buf.length);
/*
* 阻塞接收数据
*/
socket.receive(dp);
/*
*把获取的数据打印出来
*/
String ip=dp.getAddress().getHostAddress();
String message=new String(dp.getData(),0,dp.getLength());
System.out.println(ip+"说:"+message);
if("886".equals(message))
{
System.out.println(ip+":已经退出");
break;
}
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}