日期:2014-05-20 浏览次数:21106 次
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class App { private static ServerSocket server; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("正在创建服务器……"); try { server = new ServerSocket(10086); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("创建服务器时出现异常(IOException)!"); return; } System.out.println("服务器已建立。"); new Waiter(); } private static class Waiter implements Runnable { Thread thread; Socket socket; InputStream reader; OutputStream writer; int info = 0; public Waiter() { thread = new Thread(this); thread.start(); } @Override public void run() { // TODO Auto-generated method stub System.out.println("正在等待客户端连接……"); try { socket = server.accept(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("等待客户端连接时出现异常(IOException)!"); return; } System.out.println("客户端已连接。"); System.out.println("正在获取I/O通道……"); try { /*reader = new BufferedReader(new InputStreamReader( socket.getInputStream()));*/ reader = socket.getInputStream(); /*writer = new BufferedWriter(new OutputStreamWriter( socket.getOutputStream()));*/ writer = socket.getOutputStream(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("获取I/O通道时出现异常(IOException)!"); return; } System.out.println("成功获取I/O通道。"); System.out.println("正在输出信息……"); try { writer.write(9); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("输出信息时出现异常(IOException)!"); return; } System.out.println("成功输出信息:9。"); System.out.println("正在等待输入信息……"); try { while(reader.available()<1); } catch (IOException e1) { // TODO Auto-generated catch block System.out.println("等待输入信息时出现异常(IOException)!"); return; } System.out.println("有输入信息。正在读取……"); try { info = reader.read(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("读取输入信息时出现异常(IOException)!"); return; } System.out.println("成功读取输入信息。读取到的数据是:" + Integer.toString(info)); System.out.println("正在关闭socket……"); try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("关闭socket时出现异常(IOException)!"); return; } System.out.println("socket已关闭。"); System.out.println("正在关闭服务器……"); try { server.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("关闭服务器时出现异常(IOException)!"); return; } System.out.println("服务器已关闭。"); } } }