Java Socket 7部曲

Client:

Socket socket = new Socket("localhost", 8882); //初始化socket,如果是server端则多一个ServerSocket的初始化



BufferedReader sis = new BufferedReader(new InputStreamReader(System.in)); //获得系统输入流



BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream())); //得到socket的输入流,就是从server 发送过来的字符



PrintWriter os = new PrintWriter(socket.getOutPutStream()); //得到socket的输出流,就是即将发送到server的管道



string readLine = sis.readLine(); //获得系统输入的一行



while(!readLine.equals("bye")) { 



          os.println(readLine); //向服务器发送字符流



          os.flush();



          System.out.println("Client: " + readLine + "Server: " + is.readLine());



          readLine = sis.readLine();



    }



is.close(); // 关闭流



os.close();



socket.close();

Server:

ServerSocket server = new ServerSocket(8882);



Socket socket = server.accept(); //初始化socket,server端多一个ServerSocket的初始化



BufferedReader sis = new BufferedReader(new InputStreamReader(System.in)); //获得系统输入流



BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream())); //得到socket的输入流,就是从server 发送过来的字符



PrintWriter os = new PrintWriter(socket.getOutPutStream()); //得到socket的输出流,就是即将发送到server的管道



string readLine = sis.readLine(); //获得系统输入的一行



while(!readLine.equals("bye")) { 



          os.println(readLine); //向服务器发送字符流



          os.flush();



          System.out.println("Client: " + readLine + "Server: " + is.readLine());



          readLine = sis.readLine();



    }



is.close(); // 关闭流



os.close();



socket.close();



MultiThread SocketServer:

public SocketServer extends Thread {



     public static void main(String[] args) {



          ServerSocket server = new ServerSocket(8882);



          while(true) {



                    Socket socket = server.accept();



          }



     }



     public void run() {



          // Left 6 steps



     }



}

你可能感兴趣的:(java socket)