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("建立连接出错!");
  }

  
 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值