socket點對點通訊(基於模擬器)

來源:互聯網
上載者:User

socket通訊是有關伺服器與用戶端之間的通訊,要實現點對點通訊,記得抓住唯一標誌,我在這裡是獲得訪問服務端的用戶端ip地址,儲存在map中,然後通過ip地址過濾一些沒必要接受的資訊。具體實現方式如下:

首先得建立好服務端:

public class SimpleServer
{

    public static ArrayList<Socket> socketList = new ArrayList<Socket>();
    public static ArrayList<Map<String, Socket>> arrayList = new ArrayList<Map<String,Socket>>();
    public static Map<String, Socket> map = new HashMap<String, Socket>();
    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException
    {
                        
        ServerSocket ss = new ServerSocket(30000);
       
        while(true){
           
            Socket s = ss.accept();
            InetAddress in = s.getInetAddress();

            String inetAddress = in.getHostAddress();
            map.put(in.getHostAddress(), s);//存放用戶端訪問服務的ip地址
            socketList.add(s, inetAddress);// 存放Client Access Server的socket
            
            new Thread(new ServerThread(s)).start();
        }
       
    }

}

 

服務端線程:

public class ServerThread implements Runnable
{

    private Socket s = null;
    private BufferedReader br = null;
    public ServerThread(Socket s) throws IOException
    {
            this.s = s;
            if(!inetAddress.equals("170.81.304.112")&&!inetAddress.equals("170.81.304.47")){// 注意:這裡的ip為自己和對方的ip地址,下同
                br = null;
            }
            else {
                br = new BufferedReader(new InputStreamReader(s.getInputStream(), "utf-8"));
            }
    }

    @Override
    public void run()
    {
        // TODO Auto-generated method stub
        try
        {
            String content = null;

            while ((content = readFromClient()) != null)
            {
                for (Socket s : SimpleServer.socketList)
                {
                    if(!s.getInetAddress().getHostAddress().equals("170.81.304.112")&&!s.getInetAddress().getHostAddress().equals("170.81.304.47")){
                       
                    }
                    else{
                        OutputStream os = s.getOutputStream();
                        os.write((content + "\n").getBytes("utf-8"));
                    }
                   
                }
                    }
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private String readFromClient()
    {
        if(br != null){
            try
            {
                return br.readLine();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
//                    SimpleServer.socketList.remove(s);
            }
        }

        return null;
    }

}

用戶端代碼:

 

public class Client extends Activity
{
    private EditText inputEditText = null;
    private TextView content = null;
    private Button sendMsg = null;
    Socket s;
   
    OutputStream os;

    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg)
        {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            content.append("\n"+msg.obj.toString());
            Log.v("Jeny", "-----------"+content);
        }
       
    };
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.client);
        initWidget();
        try
        {
            s = new Socket("10.81.34.112", 30000);
            new Thread(new ClientThread(s, handler)).start();
            os = s.getOutputStream();
        }
        catch (UnknownHostException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        sendMsg.setOnClickListener(new OnClickListener()
        {
           
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                try
                {
                   os.write((inputEditText.getText().toString()+"\r\n").getBytes("utf-8"));
                    inputEditText.setText("");
                }
                catch (UnsupportedEncodingException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
   
    private void initWidget(){
        inputEditText = (EditText) findViewById(R.id.input);
        content = (TextView) findViewById(R.id.content);
        sendMsg = (Button) findViewById(R.id.sendMsg);
    }
}

用戶端線程:

public class ClientThread implements Runnable
{

    private Socket s;
   
    private Handler handler;
   
    BufferedReader br;
   
    public ClientThread(Socket s, Handler handler) throws IOException{
       
        this.s = s;
        this.handler = handler;
        br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    }
   
    @Override
    public void run()
    {
        // TODO Auto-generated method stub
       
        try
        {
            String content = null;
            while((content = br.readLine())!= null){
                Message msg = new Message();
                msg.obj = content;
                handler.sendMessage(msg);
            }
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.