用UDP写的群聊程序

//客户端的发射兼收取信息


package com.sxt;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class ClientNew extends Thread {
private DatagramSocket ds;


// 含参构造
public ClientNew(DatagramSocket ds) {
this.ds = ds;
}


// 接收中线程的run方法
public void run() {
byte[] b = new byte[1024];
DatagramPacket ndp = new DatagramPacket(b, b.length);
try {
ds.receive(ndp);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(new String(b).trim());
}


public static void main(String[] args) throws Exception {

DatagramSocket ds = new DatagramSocket(8800);
ClientNew cn = new ClientNew(ds);

while (true) {

// 接收(客户端)

cn.start();
// 发射(服务器)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.getBytes().length,
InetAddress.getByName("127.0.0.1"), 8866);
ds.send(dp);
}
}


}

//服务器的接收兼发射

package com.sxt;


import java.io.IOException;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;


public class ServerNew extends Thread {
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DatagramSocket ds;
static HashMap al = new HashMap();
static StringBuffer sb = new StringBuffer();
public ServerNew(DatagramSocket ds) {
this.ds = ds;
}


public void run() {
Set ks = al.keySet();
for (String k : ks) {
DatagramPacket ndp = new DatagramPacket(sb.toString().getBytes(), sb.toString().getBytes().length,
al.get(k), 8800);
try {
ds.send(ndp);
} catch (IOException e) {
e.printStackTrace();
}
}


}


public static void main(String[] args) throws Exception {
// 服务器收
DatagramSocket ds = new DatagramSocket(8866);


while (true) {
byte[] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, b.length);


ds.receive(dp);
String str = new String(b);
System.out.println(str.trim());
InetAddress ad = dp.getAddress();
al.put(ad.getHostAddress(), ad);
// 发


sb.append(ad.getHostAddress()).append(":").append(str.trim()).append(":").append(sdf.format(new Date()))
.append("\n");


ServerNew sn = new ServerNew(ds);
sn.start();
}
}
}

你可能感兴趣的:(java)