首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 互联网 >

HTTP Server之回信服务器

2012-07-31 
HTTP Server之回声服务器import java.io.IOException/** * Entry is HTTP Server entry, each socket cre

HTTP Server之回声服务器

import java.io.IOException;/** * Entry is HTTP Server entry, each socket create a thread * @author hui.wang * */public class Entry {public static void main(String[] args){try{Server server = new Server(8080);server.run();} catch(IOException e) {System.err.println("Error binding the specified port.");}}}

?

import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.net.Socket;/** * Service support echo input to output * @author hui.wang * */public class Service extends Thread {private Socket _socket;public Service(Socket socket) {_socket = socket;}public void run(){try{//Wrapper the InputStream to BufferedReaderBufferedReader input = new BufferedReader(new InputStreamReader(_socket.getInputStream()));//Wrapper the OutputStream to BuffedWriterBufferedWriter output = new BufferedWriter(new OutputStreamWriter(_socket.getOutputStream()));String line = input.readLine();while( line != null ) {if(line.equals("quit"))return;output.write(line + "\r\n");output.flush();line = input.readLine();}input.close();output.close();} catch(IOException e){//Abandon the current connection} finally{try{//Close the connection._socket.close();} catch(IOException e){//Eat the IOException}}}}

?

import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;/** * One server instance, create service to execute operation. * @author hui.wang * */public class Server implements Runnable {private ServerSocket _server;public Server(int port) throws IOException {// This statement will throw out IOException// if the specified port is not available._server = new ServerSocket(port);}public void run() {try {for (;;) {// Accept an incoming connection.Socket client = _server.accept();// Create a Service Thread to serve the client.Service service = new Service(client);service.start();}} catch (IOException e) {// Eat the IOException}}}
?

?

热点排行