package com.itjob.javanetwork;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * "第4章 Java的网络编程" -> "Sock编程" -> 考题2
 * 编写Socket客户端和服务器程序，客户端发送一个包含多个数字的字符串给服务器，服务器排序后返回给客户端，
 * 要求服务器能连续不断的服务。客户端执行：
 * java NumberSender -i 127.0.0.1 -p 8888 -d 99|789|3|0|-66
 * 服务器端回送结果为：-66|0|3|99|789
 * @author AmigoXie
 */
public class NumberSocketServer {
	public static void main(String[] args) throws Exception { 
		ServerSocket sc = new ServerSocket(8888); 
		PrintWriter out = null;
		BufferedReader in = null;
		while(true){ 
			try {
				Socket socket = sc.accept(); 
				out = new PrintWriter(socket.getOutputStream(), true);; 
				in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
				// 将接收到的数字参数放到数组中
				String line = in.readLine();
				System.out.println("接收到的数字：" + line);
				String[] paramArray = line.split("\\|");
				int[] numArray = new int[paramArray.length];
				int i = 0;
				for(i = 0 ;i < numArray.length;i++) {
					numArray[i] = Integer.parseInt(paramArray[i]); 
				} 
				
				// 将数组中的值按照从小到大的顺序排列（冒泡排序算法）
				for(i = 1; i < numArray.length; i++){ 
					for(int j = 0;j < numArray.length - 1;j++){ 
						if(numArray[i] < numArray[j]) {
							int temp = numArray[i];
							numArray[i]=numArray[j];
							numArray[j] = temp;
						} 
					}  
				}  
				
				// 给客户端程序发送信息
				StringBuffer outputStr = new StringBuffer();
				for(i=0; i < numArray.length; i++) {
					outputStr.append(numArray[i]);
					if (i != numArray.length - 1) {
						outputStr.append("|");
					}
				}  
				out.println(outputStr.toString());
				out.close();
				in.close();
				socket.close();
			} catch(Exception ex) {
				ex.printStackTrace();
			}
		}  
	} 
}
