基于TCP协议的服务器(单线程)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
 
public class JabberServer
{
 
    public static void main(String[] args) throws IOException
    {
        // TODO 自动生成的方法存根
        new FuWuQi();
    }
 
}
 
class FuWuQi
{
    public static final int port = 8080;
 
    BufferedReader in = null;
    PrintWriter out = null;
 
    class JieShou extends TimerTask
    {
        public void run()
        {
            String string=null;
            try
            {
                string=in.readLine();
                if(string!=null)
                {
                    System.out.println(string);
                }
 
            } catch (Exception e)
            {
                // TODO: handle exception
            }
 
        }
    }
 
 
    public FuWuQi() throws IOException
    {
        ServerSocket s = new ServerSocket(port);// 创建一个服务器对象 它扫描的端口是 port
        System.out.println("开始");
        try
        {
            Socket socket = s.accept();// 此时程序会进入阻塞状态 即等待一个客户端连接 但 其他程序会正常
            try
            {
                System.out.println("有一个客户机连接" + socket);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);// true 参数可以 自动刷新流 若没有刷新 信息就不会进入网络除非缓冲区溢出
                // PrintWriter out=new PrintWriter(socket.getOutputStream(),true);
 
                Timer timer=new Timer();
                JieShou jieShou=new JieShou();
 
 
                timer.schedule(jieShou, 10,200);
                while(true)
                {
                    Scanner in1=new Scanner(System.in);
                    out.println(in1.next());
                }
            //    timer.cancel();
 
 
            } catch (Exception e)
            {
 
            } finally
            {
                System.out.println("客户端 关闭");
                socket.close();// 套接字使用了非常重要的内存资源 所以一定要在用完之后关闭他们
            }
 
        } catch (Exception e)
        {
            // TODO: handle exception
        } finally
        {
            System.out.println("服务端关闭");
            s.close();
            System.exit(0);
        }
 
    }
}
posted @ 2016-07-29 11:36  -梦里不知身是客  阅读(260)  评论(0编辑  收藏  举报