本帖最后由 夜袭和尚庙 于 2019-6-3 11:43 编辑
该软件基于UDP发包 总而言之就是非常非常的low
刚学到网络编程 所以尝试写了一个 不足的地方请各位指导
代码如下:
[Asm] 纯文本查看 复制代码 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 ChatTest {
private static final int BUF_SIZE = 1024*1024;
public static void main(String[] args) {
System.out.println("欢迎使用内网聊天软件!输入886即可退出软件! ");
//创建线程任务
Send s = new Send();
Receive r = new Receive();
//创建线程对象
Thread t1 = new Thread(s);
Thread t2 = new Thread(r);
//启动线程任务,接收端先启动 发送端后启动
t2.start();
t1.start();
}
}
//发送端
class Send implements Runnable{
//创建DatagramSocket
private DatagramSocket ds = null;
public void run() {
try {
//本机发送端口为30005
ds = new DatagramSocket(30005);
} catch (SocketException e) {
System.out.println("30005发送端口已被占用!请检查!!");
return;
}
//键盘录入流
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
//字节缓冲区
byte[] data;
String line = null;
try {
while((line = bufr.readLine())!=null) {
//将键盘获取的数据转换成字节数组
data = line.getBytes();
//创建一个DatagramPacket对象 向内网中的所有用户发送广播 端口为30004
DatagramPacket dp=new DatagramPacket(data, data.length,InetAddress.getByName("192.168.82.255"),30004);
//发送数据
ds.send(dp);
if(line.equals("886")){
System.out.println("您已退出聊天室!!");
//释放流(感觉脱裤子放屁)
ds.close();
//结束程序
System.exit(0);
}
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//接收端
class Receive implements Runnable{
private static final int BUF_SIZE = 1024*1024;
private DatagramSocket ds = null;
@Override
public void run() {
try {
ds = new DatagramSocket(30004);
} catch (SocketException e) {
System.out.println("30004接收端口已被占用!请检查!!");
return;
}
//数据缓冲区
byte[] buf = new byte[BUF_SIZE];
//创建Datagrampacket对象
DatagramPacket dp = new DatagramPacket(buf,BUF_SIZE);
String data;
try {
while(true) {
ds.receive(dp);
//解析接收数据的IP
String ip = dp.getAddress().getHostAddress();
//转换成字符串
data = new String(dp.getData(),0,dp.getLength());
//输出字符串
System.out.println(ip+":"+data);
if(data.equals("886")) {
System.out.println(ip+"已退出聊天室! 網絡一線牽 珍惜這份緣~");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} |