package com.itjob.javanetwork;

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

/**
 * 服务端Socket类
 * @author AmigoXie
 */
public class Server {
	private ServerSocket ss;
	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;
	
	public Server() {
		try {
			// 在服务器指定端口10000创建队列长度为50的服务器套接字
			ss = new ServerSocket(10000);
			while (true) {
				// 告诉服务器不停地等待，直到有客户端连接到该ServerSocket指定的端口
				// 一旦有客户端通过网络向该端口发送正确的连接请求，该方法就会返回表示服务器与客户端连接已建立的Socket对象
				socket = ss.accept();
				String clientIP = socket.getInetAddress().getHostAddress();
				String clientPort = ":" + socket.getLocalPort();
				System.out.println("A client come in! IP:" + clientIP + clientPort);
				// 获得客户端发送的消息
				in = new BufferedReader(new InputStreamReader(
						socket.getInputStream()));
				String line = in.readLine();
				System.out.println("Client send is:" + line);
				// 给客户端Socket发送回应消息
				out = new PrintWriter(socket.getOutputStream(), true);
				out.println("Server:Your Message Received!");
				// 关闭资源
				out.close();
				in.close();
				socket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new Server();
	}
}
