package com.crazy.tcpdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Looper;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "tcp";
EditText mEdServerIp;
EditText mEdServerPort;
EditText mEdServerSendMessage;
ListView mLvServerMsg;
EditText mEdClientIp;
EditText mEdClientPort;
EditText mEdClientSendMessage;
ListView mLvClientMsg;
Button btn_start_server;
Button btn_server_send;
Button btn_server_clear_message;
Button btn_start_client;
Button btn_client_send;
Button btn_client_clear_message;
private List<String> mServerMessageList;
private List<String> mClientMessageList;
private ArrayAdapter<String> mServerMessageAdapter;
private ArrayAdapter<String> mClientMessageAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//android.os.NetworkOnMainThreadException
//简单暴力,强制使用,代码修改简单(但是非常不推荐)
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
initView();
initData();
}
private void initView() {
mEdServerIp = findViewById(R.id.ed_server_ip);
mEdServerPort = findViewById(R.id.ed_server_port);
mEdServerSendMessage = findViewById(R.id.ed_server_send_message);
mLvServerMsg = findViewById(R.id.lv_server_msg);
mEdClientIp = findViewById(R.id.ed_client_ip);
mEdClientPort = findViewById(R.id.ed_client_port);
mEdClientSendMessage = findViewById(R.id.ed_client_send_message);
mLvClientMsg = findViewById(R.id.lv_client_msg);
btn_start_server = findViewById(R.id.btn_start_server);
btn_server_send = findViewById(R.id.btn_server_send);
btn_server_clear_message = findViewById(R.id.btn_server_clear_message);
btn_start_client = findViewById(R.id.btn_start_client);
btn_client_send = findViewById(R.id.btn_client_send);
btn_client_clear_message = findViewById(R.id.btn_client_clear_message);
btn_start_server.setOnClickListener(this);
btn_server_send.setOnClickListener(this);
btn_server_clear_message.setOnClickListener(this);
btn_start_client.setOnClickListener(this);
btn_client_send.setOnClickListener(this);
btn_client_clear_message.setOnClickListener(this);
}
private void initData() {
String serverIp = getLocalIpAddress();
Log.e(TAG, "initData serverIp=" + serverIp);
mEdServerIp.setText(serverIp);
mEdClientIp.setText(serverIp);
mServerMessageList = new ArrayList<>();
mClientMessageList = new ArrayList<>();
mServerMessageAdapter = new ArrayAdapter<>(this, R.layout.item_log, R.id.item_log, mServerMessageList);
mClientMessageAdapter = new ArrayAdapter<>(this, R.layout.item_log, R.id.item_log, mClientMessageList);
mLvServerMsg.setAdapter(mServerMessageAdapter);
mLvClientMsg.setAdapter(mClientMessageAdapter);
}
@Override
public void onBackPressed() {
super.onBackPressed();
// 杀死该应用进程
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
private void getServerPort() {
mServerPort = Integer.parseInt(mEdServerPort.getText().toString().trim());
}
private void getServerSendMessage() {
mServerSendMessage = mEdServerSendMessage.getText().toString().trim();
}
private void getClientPort() {
mClientPort = Integer.parseInt(mEdClientPort.getText().toString().trim());
}
private void getClientIp() {
mClientIp = mEdClientIp.getText().toString().trim();
}
private void getClientSendMessage() {
mClientSendMessage = mEdClientSendMessage.getText().toString().trim();
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_start_server:
getServerPort();
new ServerSocketThread().start();
break;
case R.id.btn_server_send:
getServerSendMessage();
serverSendMessage();
break;
case R.id.btn_server_clear_message:
mServerMessageList.clear();
mServerMessageAdapter.notifyDataSetChanged();
break;
case R.id.btn_start_client:
getClientIp();
getClientPort();
new ClientSocketThread().start();
break;
case R.id.btn_client_send:
getClientSendMessage();
clientSendMessage();
break;
case R.id.btn_client_clear_message:
mClientMessageList.clear();
mClientMessageAdapter.notifyDataSetChanged();
break;
}
}
//=================================================================================
// Server
//=================================================================================
private int mServerPort;
private String mServerSendMessage;
private List<Socket> mSocketList = new ArrayList<>();
private List<ServerReceiveRunnable> mServerReceiveRunnableList = new ArrayList<>();
class ServerSocketThread extends Thread {
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(mServerPort);
String logStart = getTime()
+ " 服务器已启动...";
logServer(logStart);
while (true) {
Socket socket = serverSocket.accept();
boolean isContain = false;
int index = 0;
for (Socket s : mSocketList) {
if (s.getInetAddress().equals(socket.getInetAddress())) {
isContain = true;
break;
}
index++;
}
if (isContain) {
Log.d(TAG, "isContain");
mServerReceiveRunnableList.remove(index).close();
mSocketList.remove(index);
}
mSocketList.add(socket);
String logAccept = getTime()
+ " 服务端地址:" + socket.getLocalAddress()
+ " 客户端地址:" + socket.getInetAddress()
+ " 新的客户端接入,当前客户端数:" + mSocketList.size();
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
最近有个项目模块需要用到TCP Socket通讯,遇到了一个大坑,所以做了这个Demo。 本Demo主要实现了安卓(Android)TCP 客户端(Client)和服务器(Server)Demo的Socket通讯。以及对接硬件的项目数据在十六进制&&byte&&int的转换处理。 要注意BufferedReader的readLine()方法的阻塞问题: 读取socket输入流的时候很多代码都会这么写,一般也不会有什么问题,但是readLine()方法读取不到换行和回车时会阻塞! String line = null; while ((line = br.readLine()) != null) { } 具体可以先查看博文:https://blog.csdn.net/daokedream/article/details/113918467,欢迎交流。
资源推荐
资源详情
资源评论
收起资源包目录
TCPDemo.zip (47个子文件)
TCPDemo
gradlew 5KB
settings.gradle 44B
.idea
runConfigurations.xml 575B
misc.xml 365B
gradle.xml 649B
codeStyles
Project.xml 3KB
vcs.xml 188B
gradle
wrapper
gradle-wrapper.properties 238B
gradle-wrapper.jar 53KB
gradlew.bat 2KB
gradle.properties 1KB
.gitignore 222B
app
src
androidTest
java
com
crazy
tcpdemo
ExampleInstrumentedTest.java 750B
test
java
com
crazy
tcpdemo
ExampleUnitTest.java 379B
main
AndroidManifest.xml 893B
res
mipmap-hdpi
ic_launcher.png 3KB
ic_launcher_round.png 5KB
mipmap-xxxhdpi
ic_launcher.png 9KB
ic_launcher_round.png 15KB
mipmap-xhdpi
ic_launcher.png 4KB
ic_launcher_round.png 7KB
mipmap-anydpi-v26
ic_launcher.xml 276B
ic_launcher_round.xml 276B
mipmap-mdpi
ic_launcher.png 2KB
ic_launcher_round.png 3KB
drawable
ic_launcher_background.xml 6KB
layout
item_log.xml 306B
activity_main.xml 8KB
drawable-v24
ic_launcher_foreground.xml 2KB
values
colors.xml 214B
strings.xml 73B
styles.xml 394B
dimens.xml 216B
mipmap-xxhdpi
ic_launcher.png 6KB
ic_launcher_round.png 10KB
java
com
crazy
tcpdemo
TcpClient.java 6KB
MainActivity.java 23KB
IntByteStringHexUtil.java 3KB
TcpServer.java 8KB
doc
tcpdemo.gif 499KB
readme 0B
1.png 33KB
2.png 93KB
.gitignore 8B
build.gradle 954B
proguard-rules.pro 772B
build.gradle 585B
共 47 条
- 1
Crazy程序猿2020
- 粉丝: 519
- 资源: 31
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
- 1
- 2
- 3
- 4
- 5
- 6
前往页