package com.iaiai.test;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
*
* <br/>
* Title: Main.java<br/>
*
* Http: iaiai.iteye.com<br/>
* Create time: 2013-1-29 上午11:41:09<br/>
* <br/>
*
* @author 丸子
* @version 0.0.1
*/
public class Main {

private DatagramSocket ds;
private int port;

public Main(int port) throws IOException {
this.port = port;
ds = new DatagramSocket(port);
// ds.setBroadcast(true);
}

public static void main(String[] args) throws Exception {
int port = 9876;
Main main = new Main(port);
main.start();
}

void start() throws Exception {
startServer();
Scanner scanner = new Scanner(System.in);
String name = "";
while (name.isEmpty()) {
System.out.print("请输入名称:");
name = scanner.nextLine();
}
String msg = "";
while (!"exit".equalsIgnoreCase(msg)) {
if (!msg.isEmpty()) {
send(name, msg);
}
System.out.print("输入消息:>");
msg = scanner.nextLine();
}
System.exit(0);
}

private void send(String name, String msg) throws IOException {
String sendMsg = encoder(name) + "," + encoder(msg);
try {
byte[] buf = sendMsg.getBytes("UTF-8");
DatagramPacket dp = new DatagramPacket(buf, buf.length);
dp.setSocketAddress(new InetSocketAddress("255.255.255.255", port));
ds.send(dp);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

private static String encoder(String str) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
return "";
}
}

private void startServer() throws SocketException {
ExecutorService threadPool = Executors.newCachedThreadPool();
threadPool.submit(new UdpReceive(ds));
}

static class UdpReceive implements Runnable {
private DatagramSocket ds;

UdpReceive(DatagramSocket ds) {
this.ds = ds;
}

@Override
public void run() {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
while (true) {
try {
ds.receive(dp);
String str = new String(dp.getData(), dp.getOffset(), dp.getLength());
String[] msgs = str.split(",");
String name = decode(msgs[0]);
String msg = decode(msgs[1]);
System.out.println(name + " 说:" + msg + " (" + dp.getSocketAddress() + ")");
// System.out.println("收到来自:"+dp.getSocketAddress()+"的消息 "+new
// String(dp.getData(),dp.getOffset(),dp.getLength()));
} catch (IOException e) {
e.printStackTrace();
}
}
}

private static String decode(String str) {
try {
return URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
return "";
}
}
}

}