网络程序设计-为多个客户服务服务器端设计

来源:互联网 发布:aspnet源码怎么搭建 编辑:程序博客网 时间:2024/06/08 02:03
package bjfu.dianzi.wzz;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Handler;

public class MultiThreadServer {
    public static void main(String[] args) {
        try{
            ServerSocket serverSocket=new ServerSocket(8000);
            int clientNo=1;
            while(true)
            {
                Socket connectToClient =serverSocket.accept();//monitor the request from client
                System.out.println("the thread open for client is "+clientNo);
                InetAddress clientInetAddress=connectToClient.getInetAddress();//get the address
                System.out.println("customer's "+clientNo+"hostname is "+clientInetAddress.getHostName());
                System.out.println("customer's "+clienNo+"ip address is "+clientInetAddress.getHostAddress());
                ThreadHandler thread=new ThreadHandler(connectToClient,clientNo);
                Thread.start();
                clientNo++;
                
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
class ThreadHandler extends Thread
{
    private Socket connnectToClient;
    public ThreadHandler(Socket socket,int i)
    {
        connnectToClient=socket;
    }
    @Override
    public void run ()
    {
        try{
            DataInputStream isFromClient =new DataInputStream(connnectToClient.getInputStream());
            DataOutputStream osToClient =new DataOutputStream(connnectToClient.getOutputStream());
            while(true)
            {
                int num=isFromClient.readInt();
                System.out.println("the number received from client is "+num);
                int sq=num*num;
                osToClient.writeInt(sq);
                System.out.println("square number is "+sq);
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}



























0 0