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

 

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
 
class Server extends Thread
{
    private BufferedReader in = null;
    private PrintWriter out = null;
    private Socket socket = null;
    public static int count=0;
    public JabberClient dangQianClient=null;
    Scanner sc = new Scanner(System.in);
 
    class JieShou extends TimerTask
    {
 
        String temp = null;
 
        public void run()
        {
            try
            {temp = in.readLine();
            if(temp!=null)    
 
                System.out.println(temp);
 
            } catch (Exception e)
            {System.out.println( e.getMessage());
            }
        }
    }
 
    public Server(Socket socket) throws IOException
    {
 
        this.socket = socket;
        System.out.println("有一个新的客户端连接"+socket);
        System.out.println("当前的客户端数目: "+ ++count);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out = new PrintWriter(new BufferedOutputStream(socket.getOutputStream()), true);
        Timer timer = new Timer();
        timer.schedule(new JieShou(), 100, 300);
        this.start();//开始线程
    }
 
    public void run()
    {
        while (true)
        {
            String temp=sc.next();//将此写到线程内,可与当前连接客户端对话  但是 并不能知道连接的是哪个客户端
             out.println("服务器: " + temp);
        }
 
 
    }
}
 
public class MultiJabberServer
{
 
    public static final int port = 8080;
 
    public static void main(String[] args) throws IOException
    {
 
        InetAddress addr=InetAddress.getLocalHost();
        System.out.println(addr.getHostAddress());
        ServerSocket serverSocket = new ServerSocket(port);
        try
        {
            while (true)
            {
 
                Socket socket = serverSocket.accept();//循环等待客户端连接
                try
                {
                    new Server(socket);//有一个客户端连接即开始一个新的线程与客户端通信  然后继续等待客户端的连接请求
                } catch (Exception e)
                {
                    socket.close();
                }  
            }
        } finally
        {
            serverSocket.close();
            System.exit(0);
        }
    }
 
}
 
 
 
 
 
posted @ 2016-07-29 11:41  -梦里不知身是客  阅读(262)  评论(0编辑  收藏  举报