TcpService
初始化ServerSocket
class SocketAcceptThread extends Thread{
@Override
public void run() {
try {
mServerSocket = new ServerSocket(5566);
mSocket = mServerSocket.accept();
inputStream = mSocket.getInputStream();
while (true){
byte[] buffer = new byte[1024];
try {
if (null != inputStream){
inputStream.read(buffer);
String s = new String(buffer);
Message messagehand = new Message();
messagehand.obj =s;
mHandler.sendMessage(messagehand);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
Handler更新UI
@SuppressLint("HandlerLeak")
Handler mHandler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (null != msg && null != msg.obj){
String s = msg.obj.toString();
Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();
}
}
};
启动线程
new SocketAcceptThread().start();
TcpClient
初始化Socket 设置Service的ip和约定好的端口号
class SocketConnectThread extends Thread{
public void run(){
try {
mSocket = new Socket("192.168.3.186",5566);
if(mSocket != null){
outputStream = mSocket.getOutputStream();
}
} catch (Exception e) {
e.printStackTrace();
mHandler.sendEmptyMessage(MSG_SOCKET_CONNECTFAIL);
return;
}
mHandler.sendEmptyMessage(MSG_SOCKET_CONNECT);
}
}
Handler更新UI
@SuppressLint("HandlerLeak")
Handler mHandler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
}
};
发送消息 所有网络操作需要在子线程中进行
public void send(View view) {
new Thread(() -> {
try {
outputStream.write(TextUtils.isEmpty(editText.getText().toString())?"默认消息".getBytes():editText.getText().toString().getBytes());
outputStream.flush();
}catch (Exception e) {
e.printStackTrace();
}
}).start();
}
最后启动线程
new SocketConnectThread().start();
记得管理 Socker 和 ServerSocket 的生命周期。
|