服务器(多线程)

package serverAndClient;
 
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-27 13:22  -梦里不知身是客  阅读(122)  评论(0编辑  收藏  举报