TCP解决端口冲突问题

修改前一个TCP的编程实例
代码如下:
ReverseServer.java文件代码:

import java.net.*;

public class ReverseServer {

   public static void main(String[] args) {
      // TODO Auto-generated method stub
      ServerSocket ss = null;
      try {
         if (args.length < 1) {               //if和else用于解决端口冲突,如果运行时没有输入参数则为8001
            ss = new ServerSocket(8001);     //若果运行时指定了参数,则参数为端口号(如:8002)
         }
         else {
            ss = new ServerSocket(Integer.parseInt(args[0]));
         }
         boolean bRunning = true;
         while (bRunning) {
            Socket s = ss.accept();
            new Thread(new Servicer(s)).start();
         }
         ss.close();
      } catch (Exception e) {
         // TODO: handle exception
         e.printStackTrace();
      }

   }

}

Servicer.java文件代码:

import java.net.*;
import java.io.*;

public class Servicer implements Runnable {
   private Socket s = null;
   public Servicer(Socket s) {
      this.s = s;
   }
   public void run() {
      try {
         InputStream ips = s.getInputStream();
         OutputStream ops = s.getOutputStream();
         BufferedReader br = new BufferedReader(
               new InputStreamReader(ips));
         PrintWriter pw = new PrintWriter(ops,true);
         while (true) {
            String strLine = br.readLine();
            if(strLine.equalsIgnoreCase("quit"))
            {
               break;
            }
            String strEcho = (new StringBuffer(strLine).reverse()).toString();
            pw.println(strLine + "-->" + strEcho);
         }
         br.close();
         pw.close();
         s.close();
      } catch (Exception e) {
         // TODO: handle exception
         e.printStackTrace();
      }

   }
}

这样就实现了端口冲突问题,其实8001哪里也可以通过读文件来设置默认的端口,这样就可以将使用者第一次设置的端口写入文件,使用者以后就不必要每次设置,要修改可修改文件里存入的端口号。

你可能感兴趣的:(编程,String,tcp)