标签:ica hat sys readline ide sockets vat except inpu
ServerSocket只连一次的程序
package test; //只能连一次的服务器程序 //: JabberServer.java // Very simple server that just // echoes whatever the client sends. import java.io.*; import java.net.*; public class JabberServer { // Choose a port outside of the range 1-1024: public static final int PORT = 8080; public static void main(String[] args) throws IOException { ServerSocket s = new ServerSocket(PORT); System.out.println("Started: " + s); try { // Blocks until a connection occurs: Socket socket = s.accept(); try { System.out.println( "Connection accepted: "+ socket); BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream())); // Output is automatically flushed // by PrintWriter: PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream())),true); while (true) { String str = in.readLine(); if (str.equals("END")) break; System.out.println("Echoing: " + str); out.println(str); } // Always close the two sockets... } finally { System.out.println("closing..."); socket.close(); } } finally { s.close(); } } } ///:~
多服务端程序实例
/* this is serversocket */ package socket; import java.io.*; import java.net.*; class ServerOne extends Thread{ private Socket socket; private BufferedReader in; private PrintWriter out; public ServerOne(Socket s) throws IOException{ socket = s; in = new BufferedReader( new InputStreamReader( socket.getInputStream(),"UTF-8")); //Enbale auto-flush; out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream(),"UTF-8")),true); start(); } public void run(){ try{ while(true){ String str = in.readLine(); if(str.equals("END")) break; System.out.println("Echoing:" + socket.getInetAddress() + socket.getPort()); out.println(str); } }catch(IOException e){ }finally{ try{ socket.close(); }catch(IOException e){ } } } } public class MultiServer{ static final int PORT = 5000; public static void main(String[] args)throws IOException{ ServerSocket s = new ServerSocket(PORT); System.out.println("Server Started"); try{ while(true){ Socket socket = s.accept(); try{ new ServerOne(socket); }catch(IOException e){ socket.close(); } } }finally{ s.close(); } } }
标签:ica hat sys readline ide sockets vat except inpu
原文地址:https://www.cnblogs.com/jiangfeilong/p/10504030.html