/** * <p>Title:EchoServer.java </p> * <p>Description: EchoServer create a echo-like server at port 3333</p> * @author Mac * @version 2002/9/2 */
import java.net.*; import java.io.*;
public class EchoServer { public static void main (String[] args) throws IOException { ServerSocket echoServer = null; try { echoServer = new ServerSocket(3333); //creat a server socket at port 3333(问题一) } catch(IOException e) { System.err.PRintln("Couldn't listen on port:3333"); System.exit(-1); }
PrintWriter out = new PrintWriter(echoClient.getOutputStream(),true); //gets the socket's output stream and opens a PrintWriter on it //if you remove the argument true,what will happen?(问题三) BufferedReader in = new BufferedReader( new InputStreamReader(echoClient.getInputStream())); //gets the socket's input stream and opens a BufferedReader on it String strFromClient;
(客户端) /** *<p>Title:EchoClient.java </p> *<p>Description: EchoClient creates a socket thereby getting a connection to echo-like server</p> * @author Mac Wang * @version 2002/8/30 */
import java.net.*; import java.io.*;
public class EchoClient {
public static void main(String[] args) { try { Socket echoClient = new Socket("yourhostname",3333); //creat a new socket connected to host and port 3333 PrintWriter out = new PrintWriter(echoClient.getOutputStream(),true);
BufferedReader in = new BufferedReader( new InputStreamReader(echoClient.getInputStream())); String fromServer,fromUser; BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); //gets the system input stream and opens a BufferedReader on it while ((fromUser = stdIn.readLine()) != null) { if (fromUser.equals("bye")) break; //when user types "bye" then end
4、注重程序中是如何读取和写入Socket的? 5、试着多打开几个客户端,看看效果如何? 从问题5中大家可以看出来,上面的例子只支持一个用户连接,那么如何支持多用户的同时访问呢?最简单有效的方法就是利用多线程实现,每个线程对应一个用户连接,server接受一个client连接后,就新产生一个线程,并交由它去处理余下的工作。下面就是支持多用户的服务器端实现: /** *<p>Title:EchoMultiServer </p> *<p>Description: EchoServer create a echo-like server at port 3333 which supports multi-client</p> * @author Mac Wang * @version 2002/9/2 */ import java.net.*; import java.io.*; class EchoMultiServerThread extends Thread { private Socket echoClient = nul