socket点对点通信(基于模拟器)

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);// 存放客户端访问服务器的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();
        }
    }

}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值