//主方法package comhuhaidemosocket
public class Main {
/** 功能說明* @param args * @author 胡海* @throws InterruptedException * @since 下午 */
public static void main(String[] args) throws InterruptedException { Thread serverTthread = new Thread(new Runnable(){ public void run(){ new SocketServer()} })serverTthreadstart()Threadsleep()Thread clientThread = new Thread(new Runnable(){ public void run(){ new SocketClient()} })clientThreadstart()}
}
//客戶端<pre name=code class=java>package comhuhaidemosocket
import javaioBufferedReaderimport javaioInputStreamReaderimport javaioPrintWriterimport Socket
public class SocketClient { private Socket socketprivate int port = private String hostIp =
public SocketClient(){ try { String message = nullBufferedReader in = nullPrintWriter out = nullBufferedReader line = nullwhile(!SocketCommandCONST_QUITequals(message)){ socket = new Socket(hostIp port)in = new BufferedReader(new InputStreamReader(socketgetInputStream()))out = new PrintWriter(socketgetOutputStream() true)line = new BufferedReader(new InputStreamReader(Systemin))
Systemoutprintln(please input some characters )message = linereadLine()outprintln(message)Systemoutprintln(Back message from server[ + inreadLine() + ])} Systemoutprintln(Client exit)lineclose()outclose()inclose()socketclose()} catch (Exception e) { eprintStackTrace()}
public static void main(String[] args) { new SocketClient()
}
}
//服務端view plain package comhuhaidemosocket
import javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamReaderimport javaioPrintWriterimport ServerSocketimport Socketimport ncurrentExecutorServiceimport ncurrentExecutors
public class SocketServer { private ServerSocket serverSocketprivate Socket socketprivate int port = private ExecutorService executeService = ExecutorsnewFixedThreadPool()
public SocketServer(){ try { serverSocket = new ServerSocket(port)// serverSocket = new ServerSocket(port InetAddressgetByName())Systemoutprintln(SocketServer have been started[ + serverSocket + ])while(true){ socket = serverSocketaccept()executeServicesubmit(new Runnable(){ public void run(){ try{ BufferedReader in = new BufferedReader(new InputStreamReader(socketgetInputStream()))PrintWriter out = new PrintWriter(socketgetOutputStream() true)
String line = inreadLine()Systemoutprintln(Server Received[ + line + ])outprintln(Server Received[ + line + ])outclose()inclose()}catch (Exception e) { eprintStackTrace()}finally{ try { socketclose()} catch (IOException e) { Systemoutprintln(close socket error)eprintStackTrace()} })} } catch (Exception e) { eprintStackTrace()}finally{ try { if(null != serverSocket){ serverSocketclose()Systemoutprintln(serverSocket close)} } catch (Exception e) { eprintStackTrace()}
public static void main(String[] args){ new SocketServer()}
}
//常量view plain package comhuhaidemosocket
public class SocketCommand { public static final String CONST_QUIT = quit}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25705.html