Android搭建简单的socket服务器——基于TCP


移动端基本上用http很多, 很少接触socket编程,对于在android端作为服务器更少,最近因为项目需要,要在android端搭建服务器,中转智能硬件发来的数据,所以把大学里边学习socket代码整理了下,写了个socket的简易服务器,实现了客户端连接到服务器,发送文本信息,服务器回传给客户端,有木有感觉像大学课设


废话不多说上代码..........................
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MySocketServer {

    private boolean isEnable;
    private final WebConfig webConfig;//配置信息类
    private final ExecutorService threadPool;//线程池
    private ServerSocket socket;

    public MySocketServer(WebConfig webConfig) {
        this.webConfig = webConfig;
        threadPool = Executors.newCachedThreadPool();
    }

    /**
     * 开启server
     */
    public void startServerAsync() {
        isEnable=true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                doProcSync();
            }
        }).start();
    }

    /**
     * 关闭server
     */
    public void stopServerAsync() throws IOException {
        if (!isEnable){
            return;
        }
        isEnable=true;
        socket.close();
        socket=null;
    }

    private void doProcSync() {
        try {
            InetSocketAddress socketAddress=new InetSocketAddress(webConfig.getPort());
            socket=new ServerSocket();
            socket.bind(socketAddress);
            while (isEnable){
              final Socket remotePeer= socket.accept();
                threadPool.submit(new Runnable() {
                    @Override
                    public void run() {
                        LLogger.e("remotePeer..............."+remotePeer.getRemoteSocketAddress().toString());
                        onAcceptRemotePeer(remotePeer);
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void onAcceptRemotePeer(Socket remotePeer) {
        try {
            remotePeer.getOutputStream().write("connected successful".getBytes());//告诉客户端连接成功
            // 从Socket当中得到InputStream对象
            InputStream inputStream = remotePeer.getInputStream();
            byte buffer[] = new byte[1024 * 4];
            int temp = 0;
            // 从InputStream当中读取客户端所发送的数据
            while ((temp = inputStream.read(buffer)) != -1) {
                LLogger.e(new String(buffer, 0, temp,"UTF-8"));
                remotePeer.getOutputStream().write(buffer,0,temp);//把客户端传来的消息发送回去
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


配置信息类
public class WebConfig {

    private int port;//端口
    private int maxParallels;//最大监听数

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public int getMaxParallels() {
        return maxParallels;
    }

    public void setMaxParallels(int maxParallels) {
        this.maxParallels = maxParallels;
    }
}


然后在activity中onCreate方法在开启服务即可
 WebConfig webConfig = new WebConfig();
        webConfig.setPort(9001);
        webConfig.setMaxParallels(10);
        mySocketServer = new MySocketServer(webConfig);
        mySocketServer.startServerAsync();

别忘了在onDestroy中关闭
    try {
            mySocketServer.stopServerAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

如果觉得帮助,欢迎打赏!

Android搭建简单的socket服务器——基于TCP_第1张图片 


 

你可能感兴趣的:(android,随记)