Android模拟聊天工具

本文介绍了一种使用Java实现的简单网络通信模型,通过创建客户端和服务器的DatagramSocket实例,实现了基于UDP协议的双向数据传输。客户端能够将数据发送到服务器,并从服务器接收响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

没有写界面,但是主要的代码都已经写出。
import java.io.*;
import java.net.*;
class ChatDemo
{
	public static void main(String [] args)throws Exception
	{
		DatagramSocket send1 = new DatagramSocket();
		DatagramSocket rece1 = new DatagramSocket(10001);

		new Thread(new send(send1)).start();
		new Thread(new rece(rece1)).start();
	}
}
class send implements Runnable  
{
	private DatagramSocket ds;
	public send(DatagramSocket ds)
	{
		this.ds = ds;
	}
	public void run()
	{
		try
		{
			BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));//读取键盘输入
 			String line = null;
			while((line = buf.readLine())!=null)//如果不为空,就继续读
			{
				byte [] b = line.getBytes();
				DatagramPacket dp = new DatagramPacket(b,b.length,InetAddress.getByName("192.168.33.1"),10001);//构造数据包,发送到指定主机端口
				ds.send(dp);
			}
			ds.close();
		}
		catch (Exception e)
		{
			throw new RuntimeException("发送端失败");
		}
	}
}

class rece implements Runnable
{
	private DatagramSocket ds;
	public rece(DatagramSocket ds)
	{
		this.ds = ds;
	}
	public void run()
	{
		try
		{
			while(true)
			{
				byte [] b = new byte[1024*64];
				DatagramPacket dp = new DatagramPacket(b,b.length);//接收发送过来的数据
				ds.receive(dp);
				String ip = dp.getAddress().getHostAddress();//读取IP
				String data = new String(dp.getData(),0,dp.getLength());//读取数据
				System.out.println(ip+":"+data);
			}
		}
		catch (Exception e)
		{
			throw new RuntimeException("接收端失败");
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值