Internet Programming(2)--Single Thread Socket Communication

The whole program includes two parts, server and client.  They communicate with each other by  class of ServerSocket and Socket.

Also, pay great attention to the detailed  usages of stream.

The code resources are as belows:

//SingleSocketServer.java

import java.net.*;
import java.io.*;
public class SingleSocketServer
{
 public static void main(String args[])
 {
  ServerSocket serverObj=null;
  try
  {
   serverObj=new ServerSocket(7777);
   System.out.println("ok!");
   Socket clientObj=serverObj.accept();
  String lineStr;
  InputStreamReader streamObj1=new InputStreamReader(clientObj.getInputStream());
   BufferedReader buffObj1=new BufferedReader(streamObj1);
   PrintWriter outObj=new PrintWriter(clientObj.getOutputStream());  //注意

   InputStreamReader streamObj2=new  InputStreamReader(System.in);
   BufferedReader buffObj2=new BufferedReader(streamObj2);
   System.out.println("Client: "+buffObj1.readLine());
   
   lineStr=buffObj2.readLine();  //注意
   
   while (!lineStr.equals("finish"))
   {
    outObj.println(lineStr);
    outObj.flush();
    System.out.println("Server: "+lineStr);
    System.out.println("Client: "+buffObj1.readLine());
    lineStr=buffObj2.readLine();
   }
   buffObj1.close();
   buffObj2.close();
   outObj.close();
   clientObj.close();
   serverObj.close();
   }
  catch (IOException e)
  {
   System.out.println("建立监听端口失败!");
  }
  
  
 }
}

******************************************************************

//SingleSocketClient.java

import java.net.*;
import java.io.*;
public class SingleSocketClient
{
 public static void main(String args[])
 {
  try
  {
   Socket socketObj=new Socket("127.0.0.1",7777);
   InputStreamReader streamObj1=new InputStreamReader(System.in);
   BufferedReader buffObj1=new BufferedReader(streamObj1);
   PrintWriter outObj=new PrintWriter(socketObj.getOutputStream());
   BufferedReader buffObj2=new BufferedReader(new InputStreamReader(socketObj.getInputStream()));
   String lineStr;
   lineStr=buffObj1.readLine();
   while (!lineStr.equals("finish"))
   {
    outObj.println(lineStr);
    outObj.flush();
    System.out.println("Client: "+lineStr);
    System.out.println("Server: "+buffObj2.readLine());
    lineStr=buffObj1.readLine();
    
   }
   buffObj2.close();
   buffObj1.close();
   outObj.close();
   socketObj.close();

  }
  catch (IOException e)
  {
   System.out.println("建立连接出错!");
  }

  
 }

}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页