Socket 一对多通信

服务器(TCPServer.java):

package visec;

import java.net.*;  

import java.io.*;  



public class TCPServer{  

    public static void main(String[] args) throws Exception{  

        ServerSocket ss = new ServerSocket(5566); //创建一个Socket服务器,监听1001端口  

        System.out.println("1001端口开启~~");

        int i=0;  

        //利用死循环不停的监听端口  

        while(true){  

            Socket s = ss.accept();//利用Socket服务器的accept()方法获取客户端Socket对象。  

            i++;  

            System.out.println("第" + i +"个客户端成功连接!");  

            Client c = new Client(i,s); //创建客户端处理线程对象  

            Thread t =new Thread(c); //创建客户端处理线程  

            t.start(); //启动线程  

        }  

    }  

}  

//客户端处理线程类(实现Runnable接口)  

class Client implements Runnable{  

    int clientIndex = 0; //保存客户端id  

    Socket s = null; //保存客户端Socket对象  



    Client(int i,Socket s){  

        clientIndex = i;  

        this.s = s;  

    }  

    public void run(){  

        //打印出客户端数据  

        try{  

            DataInputStream dis = new DataInputStream(s.getInputStream());  

            System.out.println("第" + clientIndex + "个客户端发出消息:" + dis.readUTF());  

            dis.close();  

            s.close();  

        }  

        catch(Exception e)  

        {}  

    }  

}  

客户端(TCPClient.java):

package visec;

import java.net.*;  

import java.io.*;  

  

public class TCPClient{  

  public static void main(String[] args) throws Exception{  

    Socket s = new Socket("192.168.0.129",5566); //创建一个Socket对象,连接IP地址为192.168.0.129的服务器的5566端口  

    DataOutputStream dos = new DataOutputStream(s.getOutputStream()); //获取Socket对象的输出流,并且在外边包一层DataOutputStream管道,方便输出数据  

    Thread.sleep((int)(Math.random()*200)); //让客户端不定时向服务器发送消息  

    dos.writeUTF("客户端消息--Msg"); //DataOutputStream对象的writeUTF()方法可以输出数据,并且支持中文  

    dos.flush(); //确保所有数据都已经输出  

    dos.close(); //关闭输出流  

    s.close(); //关闭Socket连接  

  }  

}  

 

你可能感兴趣的:(socket)