java-TCPIP协议学习

 

import java.io.*;

import java.net.*;

public class tcpserver {

 

         /**

          * @param args

          */

         public static void main(String[] args) {

                   // TODO Auto-generated method stub

                   try{

                            ServerSocket ss=new ServerSocket(8001);//设置端口

                            Socket s;

                            InputStream ips;

                            OutputStream ops;

                            s=ss.accept();//没有请求会一直阻塞.

                            ips=s.getInputStream();

                            ops=s.getOutputStream();//获取输入输出流

                            int num=1;

                            while(true)

                            {

                            ops.write(("hello! this is server!"+":"+num).getBytes());

                            BufferedReader br=new BufferedReader(new InputStreamReader(ips));

                            String text=br.readLine();

                            if (text.equals("quit"))//quit

                            {

                                     break;

                            }

                            //byte[] buf=new byte[1024];

                            //System.out.println(new String(buf,0,ips.read(buf)));

                            System.out.println(text);

                            num++;

                            }

                            ips.close();

                            ops.close();

                            s.close();

                            ss.close();

                   }

                   catch(Exception e)

                   {

                            e.printStackTrace();

                   }

         }

 

}

在命令行窗口用telnet测试 并输入quit退出。

你可能感兴趣的:(exception,String,socket,server,import,byte)