SocketDemo

服务端

//全局变量
    ServerSocket mServer = null;
    Socket mServerSocket = null;
//端口号
int port=8888;
1.初始化服务端
mServer = new ServerSocket(port);//客户端连接需要端口号
2.建立与客户端的连接,并监听客户端发送的内容
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //在没有客户端连接之前会一直挂起
                    mServerSocket = mServer.accept();

                    //该方法可以获取客户端的ip地址
                    SocketAddress ip = mServerSocket.getRemoteSocketAddress();

                    //监听客户端发送过来的内容
                    InputStream inputStream;
                    try {
                        inputStream = mServerSocket.getInputStream();
                        while (!mServerSocket.isClosed()) {
                            byte[] bs = new byte[5000];
                            inputStream.read(bs);
                            String string = new String(bs, "UTF-8");
                            if (TextUtils.isEmpty(string))
                                return;
                            Logger.d(string.trim()+"with服务端接收");
                        }
                    } finally {
                        mServerSocket.close();
                    }
                } catch (IOException e) {
                }
            }
        }).start();
3.发送消息给客户端

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            OutputStream outputStream =
                                    mServerSocket.getOutputStream();
                            PrintWriter printWriter = new PrintWriter(outputStream);
                            printWriter.print("服务端发送");
                            printWriter.flush();
                        } catch (IOException e) {
                        }
                    }
                }).start();

客户端

//全局变量
Socket mClientSocket = null;
//端口号,与服务初始化时的端口号相同
int port=8888;
1.初始化客户端
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                //WifiUtils.getWifiIp(context)用于获取本机的ip地址,代码稍后给出
                //因为客户端和服务端是在同一个app中运行,所以传入的ip地址直接获取本机就好
                    mClientSocket = new Socket(WifiUtils.getWifiIp(MainActivity.this), port);
                //监听服务端发送的消息
                initClientInputStream();    
                } catch (IOException e) {
                }
            }
        }).start();
2.监听服务端发送的消息
    private void initClientInputStream() {
        if (mClientSocket==null)return;
        while(!mClientSocket.isClosed()){
            try {
                InputStream inputStream = mClientSocket.getInputStream();
                byte[] bs=new byte[5000];
                inputStream.read(bs);
                String s = new String(bs, "UTF-8");
                if (TextUtils.isEmpty(s))return;
                Logger.d(s.trim()+"with客户端接收");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
3.发送消息给服务端
                try {
                    OutputStream outputStream = mClientSocket.getOutputStream();
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.print("客户端发送");
                    printWriter.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }

完整代码

页面

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.button1)
    Button mButton1;
    @BindView(R.id.btn2)
    Button mBtn2;


    ServerSocket mServer = null;
    Socket mServerSocket = null;

    Socket mClientSocket = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initLogger();
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        initServer();
        startConnection();

        initClient();
    }

    //初始化logger工具类,用于打印日志
    private void initLogger() {
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .tag("meee")
                .build();
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));
    }

    private void initClient() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mClientSocket = new Socket(WifiUtils.getWifiIp(MainActivity.this), 8888);

                    initClientInputStream();

                } catch (IOException e) {
                }
            }
        }).start();
    }

    private void initClientInputStream() {
        if (mClientSocket==null)return;
        while(!mClientSocket.isClosed()){
            try {
                InputStream inputStream = mClientSocket.getInputStream();
                byte[] bs=new byte[5000];
                inputStream.read(bs);
                String s = new String(bs, "UTF-8");
                if (TextUtils.isEmpty(s))return;
                Logger.d(s.trim()+"with客户端接收");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void initServer() {
        try {
            mServer = new ServerSocket(8888);
        } catch (IOException e) {
        }
    }

    private void startConnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //在没有客户端连接之前会一直挂起
                    mServerSocket = mServer.accept();

                    //该方法可以获取客户端的ip地址
                    SocketAddress ip = mServerSocket.getRemoteSocketAddress();

                    //监听客户端发送过来的内容
                    InputStream inputStream;
                    try {
                        inputStream = mServerSocket.getInputStream();
                        while (!mServerSocket.isClosed()) {
                            byte[] bs = new byte[5000];
                            inputStream.read(bs);
                            String string = new String(bs, "UTF-8");
                            if (TextUtils.isEmpty(string))
                                return;
                            Logger.d(string.trim()+"with服务端接收");
                        }
                    } finally {
                        mServerSocket.close();
                    }
                } catch (IOException e) {
                }
            }
        }).start();
    }

    @OnClick({R.id.button1, R.id.btn2})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button1:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            OutputStream outputStream =
                                    mServerSocket.getOutputStream();
                            PrintWriter printWriter = new PrintWriter(outputStream);
                            printWriter.print("服务端发送");
                            printWriter.flush();
                        } catch (IOException e) {
                        }
                    }
                }).start();
                break;
            case R.id.btn2:
                try {
                    OutputStream outputStream = mClientSocket.getOutputStream();
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.print("客户端发送");
                    printWriter.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}

布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.junx.socket.MainActivity">


    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="0dp"
        android:text="btn1"
        app:layout_constraintHorizontal_bias="0.503" app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent" android:layout_marginBottom="8dp"/>
    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:text="btn2" app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button1"
    />

</android.support.constraint.ConstraintLayout>

获取本地ip地址的工具类

public class WifiUtils
{

    public static String getWifiIp (Context context)
    {
        String wifiStr = "";
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        if (wifiManager.isWifiEnabled()
                && wifiManager.getWifiState() == wifiManager.WIFI_STATE_ENABLED)
        {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            if (wifiInfo != null)
            {
                int ipAddress = wifiInfo.getIpAddress();
                if (ipAddress == 0)
                {
                    wifiStr = "";
                }
                else
                {
                    wifiStr = ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff)
                            + "." + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));
                }
            }
        }
        return wifiStr;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值