2015年5月21日:
需要用到的类和包:
包:
import java.net.*;
import java.io.*;
类:
DatagramPacket
DatagramSocket
DatagramPacket 用来实现数据的发送和接收
DatagramSocket 用来实现数据包发送和接收的套接字
先上代码:
import java.io.*;
import java.net.*;
public class QQ
{
public static void main(String[] args) throws Exception
{
Send send = new Send(new DatagramSocket());
Rece rece = new Rece(new DatagramSocket(3000));
new Thread(send).start();
new Thread(rece).start();
}
}
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 str = null;
while((str = bufr.readLine()) != null)
{
byte[] buf = str.getBytes();//把字符串转换成byte类型的数组
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("172.18.177.255"), 3000);//打成数据包
ds.send(dp);
if ("886".equals(str))
break;
}
ds.close();
}
catch (Exception e)
{
System.out.println("发送端失败");
}
}
}
class Rece implements Runnable
{
private DatagramSocket ds;
public Rece(DatagramSocket ds)
{
this.ds = ds;
}
public void run()
{
try
{
String str = null;
while(true)
{
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
str = new String(dp.getData(), 0, dp.getLength());
System.out.println(dp.getAddress().getHostAddress() + ":" + str);
}
}
catch (Exception e)
{
System.out.println("接收端失败");
}
}
}
因为既要实现发送又要有接收, 那么肯定是多线程了。
先来看发送端:
1):继承Runnable接口,传入套接字参数 DatagramSocket ds
BufferedReader 是IO操作,实现从键盘上面输入。
先来看第一步:
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("1XX.18.1XX.255"), 3000);
buf表示包的数据 是byte[]类型的
所以要把字符串转换成byte[]类型 要调用getBytes()方法。
buf.length是包的长度
InetAddress,getByName("1XX.18.1XX.255");是你要发送的目的的IP地址,255表示广播,表示0-255的IP都会收到你发送的信息,相当于QQ群聊天。
3000表示端口
接着调用send方法发送
接收端
2):同样也是继承Runnable接口,传入套接字参数
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
构造用来接收长度为length的数据包
然后调用receive方法来接收
接着String str = new String(dp.getData(), 0, dp.getLength());
这是用于输出在控制台屏幕上的 把数据输出来
dp.getData() 获取返回数据的缓冲区
dp.getLength()获取将要发送和接收的数据的长度
接着就在主函数里面开始新建并启动线程 开始运行
public static void main(String[] args) throws Exception
{
Send send = new Send(new DatagramSocket());
Rece rece = new Rece(new DatagramSocket(3000));
new Thread(send).start();
new Thread(rece).start();
}
接着就可以开始和别人聊天啦!