多线程实现UDP网络聊天室

发送端

package com.sxt;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

/**
 * 客户发
 * 
 * @author Administrator
 *
 */
public class UClient {
	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		DatagramSocket ds = new DatagramSocket(4444, InetAddress.getLocalHost());
		new Thread(new Runnable() {          //内部类启动多线程,不停地接收包
			@Override
			public void run() {          
				while (true) {          
					try {
						Thread.sleep(10);
						byte b[] = new byte[1024];
						ds.receive(new DatagramPacket(b, b.length));
						System.out.println(new String(b));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		while (true) {
			String s = sc.next();
			ds.send(new DatagramPacket(("客户端:"+s).getBytes(), ("客户端:"+s).getBytes().length, InetAddress.getByName("192.168.1.116"), 5555));
		}
	}

}

接收端

package com.sxt;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

/**
 * 咨询师
 * 
 * @author Administrator
 *
 */
public class UServer {
	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		DatagramSocket ds = new DatagramSocket(5555, InetAddress.getLocalHost());
		new Thread(new Runnable() {                //内部类启动多线程
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(10);
						byte b[] = new byte[1024];
						DatagramPacket dp = new DatagramPacket(b, b.length);
						ds.receive(dp);
						System.out.println(dp.getAddress().getHostAddress()+":"+new String(b));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		while (true) {
			String s = sc.next();
			ds.send(new DatagramPacket(("服务器:"+s).getBytes(), ("服务器:"+s).getBytes().length, InetAddress.getLocalHost(), 4444));
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值