socket server

 

public static void main(String[] args) {
    String addressIP="localhost";
    int addressPort=8899;
    
    startServerSocket(addressIP,addressPort);
}

public static void startServerSocket(String addressIP,int addressPort) {
    try {
        serverSocket = new ServerSocket(addressPort);
        Socket acceptSocket = serverSocket.accept();
        
        DataInputStream dis = new DataInputStream(acceptSocket.getInputStream());
        DataOutputStream dos = new DataOutputStream(acceptSocket.getOutputStream());
        
        while(true) {
            //boolean isClosed = isServerClose(acceptSocket);//判断是否断开
            
            boolean isClosed = acceptSocket.isClosed();
            if(!isClosed) {
                InetAddress spcketAddress = acceptSocket.getInetAddress();
                String hostName = spcketAddress.getHostAddress();
                String receiveMsg = dis.readUTF();
                
                System.out.println("host name:"+hostName+"  msg:"+receiveMsg);
                
                sendData(dos);
            }
            
        }
        
        
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    
    
}

 

posted @ 2020-09-11 20:20  西北逍遥  阅读(167)  评论(0编辑  收藏  举报