├── .gitignore ├── .idea ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── gradle.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── virtue │ │ └── socketdemo │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── virtue │ │ │ └── socketdemo │ │ │ ├── MainActivity.java │ │ │ ├── bean │ │ │ └── TestBean.java │ │ │ ├── service │ │ │ └── MySocketService.java │ │ │ └── utils │ │ │ └── RequestUtil.java │ └── res │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── virtue │ └── socketdemo │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── socketlibrary ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src ├── androidTest └── java │ └── com │ └── virtue │ └── socketlibrary │ └── ExampleInstrumentedTest.java ├── main ├── AndroidManifest.xml ├── java │ └── com │ │ └── virtue │ │ └── socketlibrary │ │ ├── manager │ │ └── Socketer.java │ │ ├── type │ │ ├── BroadCastType.java │ │ ├── ParseMode.java │ │ └── ReceiveType.java │ │ └── utils │ │ ├── ChangeTypeUtil.java │ │ ├── OnReceiveListener.java │ │ ├── ResponseListener.java │ │ ├── SendBroadCastUtil.java │ │ └── SocketCode.java └── res │ └── values │ └── strings.xml └── test └── java └── com └── virtue └── socketlibrary └── ExampleUnitTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 18 | 19 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 19 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 46 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AndroidSocket # 2 | A simple Android socket communication, you're gonna love it!

3 | ![Alt text](https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497958504351&di=4b57a7e68c56540f95beb62a9bb92cc3&imgtype=0&src=http%3A%2F%2Fe.hiphotos.baidu.com%2Fbaike%2Fw%253D268%2Fsign%3D5b952a087e3e6709be0042f903c79fb8%2F34fae6cd7b899e51f3a0ec3b43a7d933c995d143ad4b2dcf.jpg)


4 | 5 | Add AndroidSocket to your project 6 | ----- 7 | 8 | #### Gradle
9 | compile 'com.virtue.androidsocket:AndroidSocket:1.0.7' 10 | 11 | #### Maven
12 | 13 | com.virtue.androidsocket 14 | AndroidSocket 15 | 1.0.7 16 | pom 17 | 18 | 19 | 20 | 21 | How do I use AndroidSocket?(使用说明) 22 | ----- 23 | 24 | #### First you need to build a service for socket communication and heartbeat tasks before you use it.(在使用之前建一个服务,用于socket通讯, 在服务中可以建立自己的心跳任务)
25 | startService(new Intent(this, MySocketService.class)); 26 | 27 | 28 | 29 | #### In the service, configure the relevant parameters.(服务中配置连接参数)
30 | Socketer.getInstance(getApplicationContext()).bindServerConnect("123.57.56.201", 20083) //配置socket地址和端口 31 | .setTimeout(15).setEncode("UTF_8") //Configure Timeout and encoding,Timeout unit is seconds配置超时时间与编码 32 | .setReceiveType(ReceiveType.SEPARATION_SIGN) //Configuring the Receive Type配置接收形式以分隔符接收 33 | .setEndCharSequence("\r\n") //"\r\n" is End for split 配置结束符 34 | .setSendMaxByteLength(1500).start(); //Send Max bytes配置一次性最多发送的消息字节数 35 | 或者or: 36 | Socketer.getInstance(getApplicationContext()).bindServerConnect("123.57.56.201", 20083) 37 | .setTimeout(15).setEncode("UTF_8") 38 | .setReceiveType(ReceiveType.FIXED_LENGTH) //Configuring the Receive Type配置接收形式以分隔符接收 39 | .setMsgLength(2048) //Fixed length receive 配置固定长度大小接收 40 | .setSendMaxByteLength(1500).start(); //配置一次性最多发送的消息字节数 41 | 42 | 43 |
44 | 45 | Case1. Auto Parse ! (自动解析包含服务器主推通知和请求响应两种数据) 46 | ----- 47 | 48 | #### If the service has unsolicited information to you, you need to register a broadcast, like this:(如果服务有主推通知消息,你需要注册以下广播)
49 | 50 | //Set parse to Auto 51 | Socketer.getInstance(MainActivity.this).setParseMode(ParseMode.AUTO_PARSE); 52 | 53 | IntentFilter intentFilter = new IntentFilter(); 54 | intentFilter.addAction(BroadCastType.SERVER_NOTICE); 55 | MessageReceiver dataReceiver = new MessageReceiver(); 56 | registerReceiver(dataReceiver, intentFilter); 57 | 58 | 59 | 60 | #### Broadcast reception is as follows:(广播接收如下)
61 | @Override 62 | public void onReceive(Context context, Intent intent) { 63 | if (intent.getAction().equals(BroadCastType.SERVER_NOTICE)) { 64 | String dataStr = intent.getStringExtra(BroadCastType.SERVER_NOTICE_DATA); 65 | Log.i(TAG, "Data given to me by the server:" + dataStr); 66 | } 67 | } 68 | 69 | 70 | 71 | #### Send a request to the server(发送请求到服务器)
72 | Socketer.getInstance(MainActivity.this).sendStrData(reDataStr, "\"seq\":100", new ResponseListener() { 73 | @Override 74 | public void onSuccess(final String data) { 75 | Log.i("Test server data", "callback data:" + data); 76 | runOnUiThread(new Runnable() { 77 | @Override 78 | public void run() { 79 | tvResponse.setText(data); 80 | } 81 | }); 82 | } 83 | 84 | @Override 85 | public void onFail(int failCode) { 86 | Log.e("Test server data", "callback error:" + failCode); 87 | } 88 | }); 89 |
90 |

其中参数1代表是请求的数据,参数2代表是返回数据中的唯一标识,可以是请求ID、token值或者能标识唯一性的字符串

91 |

Where parameter 1 represents the requested data, parameter 2 represents a unique identity in the returned data, either a request ID, a token value, or a string that uniquely identifies the uniqueness.

92 |
93 |
94 | 95 | Case2. Manually Parse!suggest.(手动解析没有服务主推通知和请求响应之分,完全由自己自定义解析) 96 | ------ 97 | 98 | #### If you want to parse the response data yourself(如果想自己解析响应数据)
99 | //Set parse to Manual 100 | Socketer.getInstance(MainActivity.this).setParseMode(ParseMode.MANUALLY_PARSE); 101 | 102 | #### Set Listener for response(设置监听响应)
103 | Socketer.getInstance(MainActivity.this).setOnReceiveListener(new OnReceiveListener() { 104 | @Override 105 | public void onConnected(Socketer socketer) { 106 | 107 | } 108 | 109 | @Override 110 | public void onDisconnected(Socketer socketer) { 111 | 112 | } 113 | 114 | @Override 115 | public void onResponse(final String data) { 116 | runOnUiThread(new Runnable() { 117 | @Override 118 | public void run() { 119 | //response data 120 | tvResponse.setTextColor(getResources().getColor(R.color.blue)); 121 | tvResponse.setText(data); 122 | //... your parse ... 123 | } 124 | }); 125 | } 126 | }); 127 | 128 | #### Send data(发送数据)
129 | Socketer.getInstance(MainActivity.this).sendStrData(reDataStr); //request 130 | 131 | 132 | 133 |

134 | 135 | Other 136 | ----- 137 | 138 | #### If you want to reconnect to other servers(如过你想重新连接另一个服务器)
139 | //If the configuration of another server is different, first configure the information 140 | //如果另一服务器配置不一样请先配置信息 141 | //Socketer.getInstance(getApplicationContext()).setEncode("UTF_8"); 142 | //Socketer.getInstance(getApplicationContext()).setReceiveType(ReceiveType.SEPARATION_SIGN); 143 | //Socketer.getInstance(getApplicationContext()).setTimeout(15); ... 144 | Socketer.getInstance(getApplicationContext()).reConnectSever(ip, port); 145 | 146 |
147 | 148 | #### If you want to listen to the server connection and disconnection status(如过你想监听服务器连接与断开的状态)
149 | IntentFilter intentFilter = new IntentFilter(); 150 | intentFilter.addAction(BroadCastType.NETWORK_CONNECT_STATE); 151 | ConnectReceiver dataReceiver = new ConnectReceiver(); 152 | registerReceiver(dataReceiver, intentFilter); 153 | 154 | 155 | @Override 156 | public void onReceive(Context context, Intent intent) { 157 | if (intent.getAction().equals(BroadCastType.SERVER_NOTICE)) { 158 | boolean isConnected = intent.getBooleanExtra(BroadCastType.IS_CONNECTED, false); 159 | if(isConnected){ 160 | Log.i(TAG, "socket connected"); 161 | }else{ 162 | Log.e(TAG, "socket disconnect"); 163 | } 164 | } 165 | } 166 | 167 |

168 | 169 | Bugs and Feedback 170 | ----- 171 | 172 |

For bugs, feature requests, and discussion please use GitHub Issues

173 | 174 | 175 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 24 5 | buildToolsVersion "25.0.2" 6 | defaultConfig { 7 | applicationId "com.virtue.androidsocket" 8 | minSdkVersion 15 9 | targetSdkVersion 24 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | lintOptions { 21 | checkReleaseBuilds false 22 | abortOnError false 23 | } 24 | } 25 | 26 | dependencies { 27 | compile fileTree(include: ['*.jar'], dir: 'libs') 28 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 29 | exclude group: 'com.android.support', module: 'support-annotations' 30 | }) 31 | compile 'com.android.support:appcompat-v7:24.2.1' 32 | testCompile 'junit:junit:4.12' 33 | compile 'com.github.bumptech.glide:glide:3.7.0' 34 | compile project(':socketlibrary') 35 | compile 'com.google.code.gson:gson:2.8.1' 36 | } 37 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\Users\virtue\Android\Android_Studio_Sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/virtue/socketdemo/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.virtue.socketdemo; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.virtue.androidsocket", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 16 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /app/src/main/java/com/virtue/socketdemo/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.virtue.socketdemo; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.util.Log; 7 | import android.view.View; 8 | import android.widget.AdapterView; 9 | import android.widget.ArrayAdapter; 10 | import android.widget.Button; 11 | import android.widget.Spinner; 12 | import android.widget.TextView; 13 | import android.widget.Toast; 14 | 15 | import com.google.gson.Gson; 16 | import com.virtue.socketdemo.bean.TestBean; 17 | import com.virtue.socketdemo.service.MySocketService; 18 | import com.virtue.socketlibrary.manager.Socketer; 19 | import com.virtue.socketlibrary.type.ParseMode; 20 | import com.virtue.socketlibrary.utils.OnReceiveListener; 21 | import com.virtue.socketlibrary.utils.ResponseListener; 22 | 23 | import java.util.ArrayList; 24 | 25 | import static android.R.attr.type; 26 | 27 | public class MainActivity extends AppCompatActivity { 28 | private static final String TAG = "MainActivity"; 29 | private TextView tvRequest; 30 | private TextView tvResponse; 31 | private Button btSend; 32 | private String reDataStr; 33 | private Spinner spMode; 34 | private ParseMode parseMode = ParseMode.AUTO_PARSE; 35 | private ArrayList mList; 36 | 37 | @Override 38 | protected void onCreate(Bundle savedInstanceState) { 39 | super.onCreate(savedInstanceState); 40 | setContentView(R.layout.activity_main); 41 | //Open Service 42 | startService(new Intent(this, MySocketService.class)); 43 | initView(); 44 | initData(); 45 | initListener(); 46 | manuallyParseListener(); //手动解析有效(manually parse is valid) 47 | } 48 | 49 | private void initView() { 50 | tvRequest = (TextView) findViewById(R.id.tv_request); 51 | tvResponse = (TextView) findViewById(R.id.tv_response); 52 | spMode = (Spinner) findViewById(R.id.sp_mode); 53 | btSend = (Button) findViewById(R.id.bt_send); 54 | } 55 | 56 | private void initData() { 57 | mList = new ArrayList<>(); 58 | mList.add("auto"); 59 | mList.add("manually"); 60 | //适配器 61 | ArrayAdapter arr_adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, mList); 62 | //设置样式 63 | arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 64 | //加载适配器 65 | spMode.setAdapter(arr_adapter); 66 | 67 | Gson gson = new Gson(); 68 | TestBean codeGetModel = new TestBean(); 69 | codeGetModel.protver = "100"; 70 | codeGetModel.pkgtype = 1; 71 | codeGetModel.command = 15; 72 | codeGetModel.seq = 1000; 73 | TestBean.Inform in = codeGetModel.body; 74 | in.cmd = type; 75 | in.Phone = "18500000000"; 76 | final String json = gson.toJson(codeGetModel); 77 | // bean转字符串并发送 78 | reDataStr = json + "\r\n"; 79 | Log.i(TAG, "reDataStr-->" + reDataStr); 80 | tvRequest.setText(json); 81 | } 82 | 83 | private void initListener() { 84 | spMode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 85 | @Override 86 | public void onItemSelected(AdapterView parent, View view, int position, long id) { 87 | String str = mList.get(position).toString().trim(); 88 | if (str.equals("auto")) { 89 | Socketer.getInstance(MainActivity.this).setParseMode(ParseMode.AUTO_PARSE); 90 | parseMode = ParseMode.AUTO_PARSE; 91 | } else if (str.equals("manually")) { 92 | Socketer.getInstance(MainActivity.this).setParseMode(ParseMode.MANUALLY_PARSE); 93 | parseMode = ParseMode.MANUALLY_PARSE; 94 | } 95 | } 96 | 97 | @Override 98 | public void onNothingSelected(AdapterView parent) { 99 | Socketer.getInstance(MainActivity.this).setParseMode(ParseMode.AUTO_PARSE); 100 | parseMode = ParseMode.AUTO_PARSE; 101 | } 102 | 103 | }); 104 | 105 | btSend.setOnClickListener(new View.OnClickListener() { 106 | @Override 107 | public void onClick(View v) { 108 | switch (parseMode) { 109 | case AUTO_PARSE: 110 | autoReceiveData(); 111 | 112 | break; 113 | case MANUALLY_PARSE: 114 | boolean sendResult = Socketer.getInstance(MainActivity.this).sendStrData(reDataStr);//request 115 | if (!sendResult) { 116 | Toast.makeText(MainActivity.this, "send fail", Toast.LENGTH_SHORT).show(); 117 | } 118 | 119 | break; 120 | 121 | default: 122 | 123 | break; 124 | } 125 | } 126 | }); 127 | } 128 | 129 | 130 | private void manuallyParseListener() { 131 | Socketer.getInstance(MainActivity.this).setOnReceiveListener(new OnReceiveListener() { 132 | @Override 133 | public void onConnected(Socketer socketer) { 134 | Log.i(TAG, "服务器连接成功"); 135 | } 136 | 137 | @Override 138 | public void onDisconnected(Socketer socketer) { 139 | Log.e(TAG, "服务器断开连接"); 140 | } 141 | 142 | @Override 143 | public void onResponse(final String data) { 144 | runOnUiThread(new Runnable() { 145 | @Override 146 | public void run() { 147 | //response data 148 | tvResponse.setTextColor(getResources().getColor(R.color.blue)); 149 | tvResponse.setText(data); 150 | } 151 | }); 152 | } 153 | }); 154 | } 155 | 156 | private void autoReceiveData() { 157 | //Socketer.getInstance(MainActivity.this).reConnectSever("192.168.2.171", 20083); 158 | Socketer.getInstance(MainActivity.this).sendStrData(reDataStr, "\"seq\":1000", new ResponseListener() { 159 | @Override 160 | public void onSuccess(final String data) { 161 | Log.i("Test server data", "callback data:" + data); 162 | runOnUiThread(new Runnable() { 163 | @Override 164 | public void run() { 165 | tvResponse.setTextColor(getResources().getColor(R.color.red)); 166 | tvResponse.setText(data); 167 | } 168 | }); 169 | } 170 | 171 | @Override 172 | public void onFail(final int failCode) { 173 | Log.e("Test server data", "callback error:" + failCode); 174 | runOnUiThread(new Runnable() { 175 | @Override 176 | public void run() { 177 | Toast.makeText(MainActivity.this, "返回错误码:" + failCode, Toast.LENGTH_SHORT).show(); 178 | } 179 | }); 180 | } 181 | }); 182 | } 183 | 184 | 185 | } 186 | -------------------------------------------------------------------------------- /app/src/main/java/com/virtue/socketdemo/bean/TestBean.java: -------------------------------------------------------------------------------- 1 | package com.virtue.socketdemo.bean; 2 | 3 | import java.io.Serializable; 4 | 5 | public class TestBean implements Serializable{ 6 | 7 | 8 | public String protver; 9 | public int pkgtype; 10 | public int command; 11 | public int seq; 12 | public int terminaltype = 0; 13 | public String terminal = ""; 14 | public int result = 0; 15 | public int bodylen = 200; 16 | public Inform body=new Inform() ; 17 | 18 | public class Inform implements Serializable { 19 | public String Phone ; 20 | public int cmd; 21 | public String getPhone() { 22 | return Phone; 23 | } 24 | public void setPhone(String phone) { 25 | Phone = phone; 26 | } 27 | public int getCmd() { 28 | return cmd; 29 | } 30 | public void setCmd(int cmd) { 31 | this.cmd = cmd; 32 | } 33 | 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /app/src/main/java/com/virtue/socketdemo/service/MySocketService.java: -------------------------------------------------------------------------------- 1 | package com.virtue.socketdemo.service; 2 | 3 | import android.app.Service; 4 | import android.content.BroadcastReceiver; 5 | import android.content.Context; 6 | import android.content.Intent; 7 | import android.content.IntentFilter; 8 | import android.os.IBinder; 9 | import android.support.annotation.Nullable; 10 | import android.util.Log; 11 | 12 | import com.virtue.socketlibrary.manager.Socketer; 13 | import com.virtue.socketlibrary.type.BroadCastType; 14 | import com.virtue.socketlibrary.type.ReceiveType; 15 | 16 | /** 17 | * Created by virtue on 2017/2/16. 18 | */ 19 | 20 | public class MySocketService extends Service { 21 | 22 | private static final String TAG = "MySocketService"; 23 | private MessageReceiver dataReceiver; 24 | 25 | @Nullable 26 | @Override 27 | public IBinder onBind(Intent intent) { 28 | return null; 29 | } 30 | 31 | @Override 32 | public void onCreate() { 33 | super.onCreate(); 34 | //Demo in the LAN network, if you want to demo you need to modify your own server! 35 | Socketer.getInstance(getApplicationContext()).bindServerConnect("192.168.2.171", 20083) 36 | .setTimeout(10).setEncode("UTF_8") 37 | .setReceiveType(ReceiveType.SEPARATION_SIGN) 38 | .setEndCharSequence("\r\n") //服务器分割消息符 39 | .setMsgLength(1500).start(); 40 | IntentFilter intentFilter = new IntentFilter(); 41 | intentFilter.addAction(BroadCastType.SERVER_NOTICE); 42 | dataReceiver = new MessageReceiver(); 43 | registerReceiver(dataReceiver, intentFilter); 44 | } 45 | 46 | class MessageReceiver extends BroadcastReceiver { 47 | 48 | @Override 49 | public void onReceive(Context context, Intent intent) { 50 | if (intent.getAction().equals(BroadCastType.SERVER_NOTICE)) { 51 | String dataStr = intent.getStringExtra(BroadCastType.SERVER_NOTICE_DATA); 52 | Log.i(TAG, "Data given to me by the server:" + dataStr); 53 | } 54 | } 55 | } 56 | 57 | @Override 58 | public void onDestroy() { 59 | super.onDestroy(); 60 | if (dataReceiver != null) { 61 | unregisterReceiver(dataReceiver); 62 | Socketer.getInstance(getApplicationContext()).closeConnect(); 63 | Socketer.getInstance(getApplicationContext()).closeSocketer(); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /app/src/main/java/com/virtue/socketdemo/utils/RequestUtil.java: -------------------------------------------------------------------------------- 1 | package com.virtue.socketdemo.utils; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | import java.util.regex.PatternSyntaxException; 6 | 7 | import android.content.Context; 8 | import android.net.ConnectivityManager; 9 | import android.net.NetworkInfo; 10 | import android.telephony.TelephonyManager; 11 | 12 | public class RequestUtil { 13 | private static int requestID = 100; 14 | 15 | /** 16 | * 获取手机IMEI 17 | * 18 | * @param context 19 | * @return 20 | */ 21 | public static String getPhoneMini(Context context) { 22 | String imei = ""; 23 | TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 24 | imei = telephonyManager.getDeviceId();// 手机IMEI 25 | if (imei == null || imei.length() < 1) { 26 | imei = ""; 27 | } 28 | return imei; 29 | } 30 | 31 | /** 32 | * 检查该字符串是否只包含字母和数字 33 | * @param str 34 | * @return 35 | * @throws PatternSyntaxException 36 | */ 37 | public static boolean StringFilter(String str) throws PatternSyntaxException { 38 | // 只允许字母和数字 39 | String regEx = "[a-zA-Z0-9]{6,16}"; 40 | Pattern p = Pattern.compile(regEx); 41 | Matcher m = p.matcher(str); 42 | return m.matches(); 43 | } 44 | 45 | /** 46 | * 检查当前网络是否可用 47 | * 48 | * @param context 49 | * @return 50 | */ 51 | public static boolean isNetworkAvailable(Context context) 52 | { 53 | ConnectivityManager connectivityManager = (ConnectivityManager) context 54 | .getSystemService(Context.CONNECTIVITY_SERVICE); 55 | 56 | if (connectivityManager == null) 57 | { 58 | return false; 59 | } 60 | else 61 | { 62 | // 获取NetworkInfo对象 63 | NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo(); 64 | if (networkInfo != null && networkInfo.length > 0) 65 | { 66 | for (int i = 0; i < networkInfo.length; i++) 67 | { 68 | // 判断当前网络状态是否为连接状态 69 | if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) 70 | { 71 | return true; 72 | } 73 | } 74 | } 75 | } 76 | // 网络不可以用 77 | return false; 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 15 | 21 | 22 | 27 | 28 | 33 | 34 |