java做的聊天工具

import java.io.IOException;
import java.net.*;

public class Rec implements Runnable {

	DatagramSocket ds ;
	byte[] buf = new byte[1024];
	public void run() {
		try {
			ds =new DatagramSocket(10003);
		} catch (SocketException e) {
			System.out.println("端口被占用!");
			System.exit(1);
		}
		
		while(true)
		{
			DatagramPacket dp = new DatagramPacket(buf, 0, buf.length); 
			try {
				ds.receive(dp);
			} catch (IOException e) {
				System.out.println("接收异常!");
				System.exit(1);
			}
			String data = new String( dp.getData(),0, dp.getLength());
			InetAddress address = dp.getAddress();
			String ip = address.getHostAddress();
			String hostName = address.getHostName();
			System.out.println(data + "       Sent by: " + hostName +" "+ ip);
		}
	}

}

import java.net.*;
import java.io.*;
public class Send implements Runnable {

	DatagramSocket ds = null;
	public void run() {
		try {
			 ds = new DatagramSocket();
		} catch (SocketException e) {
			System.out.println("端口被占用!");
			System.exit(1);
		}
		
		BufferedReader br = 
				new BufferedReader(new InputStreamReader(System.in));
		String s;
		byte[] b = new byte[1024] ;
		
		try {
			while ( (s= br.readLine()) != null)
			{
				if ("886".equals(s))
				{
					break;
				}
				b = s.getBytes();
				String ip = "192.168.1.5";
				
				DatagramPacket dp = 
					new DatagramPacket(b, b.length, InetAddress.getByName(ip),10004);
				ds.send(dp);
			}
		} catch (IOException e) {
			System.out.println("输入错误!");
			System.exit(1);
			
		}
		finally
		{
			ds.close();
		}
	}

}

public class Talk {
	public static void main(String[] args) {
		Rec r =new Rec();
		Send s = new Send();
		
		Thread rec = new Thread(r);
		Thread send = new Thread(s);
		rec.start();
		send.start();
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值