Communication between H5 and H5 Communication between H5 and Andorid Communication between Andorid and Andorid H5 calls the interface through THE HTTP protocol to send messages – to mobile Android, H5, etc. Background support language: Java Front-end support language: Andorid (Java), H5 (HTML), JSP, etc. Send: send to all connections, send to all online, send to the specified user, and (send object) user not online processing note: to change the connection address, can directly use the copy code test use;
H5 and Andorid test page:
Andorid test page – The message sender sends the specified user (message receiver 1), or everyone | |
---|---|
Message Receiver 1 | Message Receiver 2 |
---|---|
Send the test page over Http
Send messages to all online users | Send a message to the specified online user |
---|---|
Test user Li Si | Test user Zhang SAN |
Java background code
Introducing dependencies:
<! -- JavA_websocket for mobile and H5 -->
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.0</version>
</dependency>
Copy the code
The Springboot project structure, which can also be spring projects, has no relation to the framework and has no impact
1.WebSocketPool custom tool class
Mainly connection pool, storage user and WebSocket connection
Custom WebSocketPool. Java
package com.dist.utils;
import org.java_websocket.WebSocket;
import java.util.*;
public class WebSocketPool {
// Connection - user name
private static final Map<WebSocket, String> userconnections = new HashMap<WebSocket, String>();
/** * Obtain the user name *@param conn
* @return* /
public static String getUserByKey(WebSocket conn) {
return userconnections.get(conn);
}
/** * get total number of online *@return* /
public static int getUserCount(a) {
return userconnections.size();
}
/** * get WebSocket *@param user
* @return* /
public static WebSocket getWebSocketByUser(String user) {
Set<WebSocket> keySet = userconnections.keySet();
synchronized (keySet) {
for (WebSocket conn : keySet) {
String cuser = userconnections.get(conn);
if (cuser.equals(user)) {
returnconn; }}}return null;
}
/** * Add connection * to the connection pool@param user
* @param conn
*/
public static void addUser(String user, WebSocket conn) {
userconnections.put(conn, user); // Add a connection
}
/** * get all connection pools */
public static Set<WebSocket> getAllWebSocket(a) {
return userconnections.keySet();
}
/** * Removes the connection * from the connection pool@param conn
* @return* /
public static boolean removeUser(WebSocket conn) {
if (userconnections.containsKey(conn)) {
userconnections.remove(conn); // Remove the connection
return true;
} else
return false;
}
/** * get all online users *@return* /
public static Collection<String> getOnlineUser(a) {
List<String> setUsers = new ArrayList<String>();
Collection<String> setUser = userconnections.values();
for (String u: setUser) {
setUsers.add(u);
}
return setUsers;
}
/** * Sends data to a specific user *@param conn
* @param message
*/
public static void sendMessageToOnlineUser(WebSocket conn, String message) {
if (null != conn) {
conn.send(message);
}
}
/** * Sends messages to all online users *@param message
*/
public static void sendMessageToOnlineAllUser(String message) {
Set<WebSocket> keySet = userconnections.keySet();
synchronized (keySet) {
for (WebSocket conn : keySet) {
String user = userconnections.get(conn);
if(user ! =null) { conn.send(message);
}
}
}
}
}
Copy the code
2. Create a room class
In order to open the room.
ChatServer.java
package com.dist.service;
import com.dist.utils.WebSocketPool;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Set;
/** * if the connection is successful, send your user name to the server, and the server will mark the user. * Step2: Send a message in the format of "XX@XXX". @ indicates the object to be sent, "all" indicates the group to be sent, and @ indicates the message to be sent. * /
public class ChatServer extends WebSocketServer {
private String username;
public ChatServer(int port) throws UnknownHostException {
super(new InetSocketAddress(port));
}
public ChatServer(InetSocketAddress address) {
super(address);
System.out.println("Address:"+address);
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
System.out.println("Connect:"+conn);
sendToAll(conn.getRemoteSocketAddress().getAddress().getHostAddress()
+ "Enter the room!);
System.out.println(conn.getRemoteSocketAddress().getAddress()
.getHostAddress()
+ "Enter the room!);
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
sendToAll(conn.getRemoteSocketAddress().getAddress().getHostAddress()
+ "Get out of the room!);
System.out.println(conn.getRemoteSocketAddress().getAddress()
.getHostAddress()
+ "Get out of the room!);
// Trigger the shutdown event
userLeave(conn);
}
// Message sent
@Override
public void onMessage(WebSocket conn, String message) {
// Check whether the message is received for the first time
boolean isfirst = true;
/*sendToAll("[" + conn.getRemoteSocketAddress().getAddress().getHostAddress() + "]" + message); * /
System.out.println("["
+ conn.getRemoteSocketAddress().getAddress().getHostAddress()
+ "]" + message);
// Check whether the connection is in the pool
Set<WebSocket> webSockets=WebSocketPool.getAllWebSocket();
for (WebSocket webSocket : webSockets){
if (webSocket.equals(conn)){
isfirst =false; }}if (isfirst) {
this.username = message;
// The client sends a message to the server
if(message ! =null) {// Determine whether the user is already online
WebSocket webSocketByUser = WebSocketPool.getWebSocketByUser(message);
if (null == webSocketByUser){
// Add the user to the connection pool - online
this.userJoin(username, conn);
System.out.println("User" + username + "Online, online number:" + WebSocketPool.getUserCount());
}else {
WebSocketPool.sendMessageToOnlineUser(conn,"["+username+"User is online, please log in another user!"); }}}else {
String[] msg = message.split("@".2);// The string is divided into XXX and XXXXX with @ delimited. MSG [0] indicates the user name sent to, and all indicates the user name sent to all
if (msg[0].equals("all")) {
sendToAll(msg[1]);
} else {
// Specify the user to send the message
sendMessageToUser(conn,msg[0], msg[1]); }}}// Exception thrown
@Override
public void onError(WebSocket conn, Exception e) {
e.printStackTrace();
if(conn ! =null) { conn.close(); }}// To all who enter the room
private void sendToAll(String text) {
Collection<WebSocket> conns = connections();
synchronized (conns) {
for(WebSocket client : conns) { client.send(text); }}}/ / test
public static void main(String[] args) throws InterruptedException,
IOException {
/*int port = 8887; ChatServer server = new ChatServer(port); server.start(); System.out.println(" room open, waiting for client access, port number: "+ server.getPort()); BufferedReader webSocketIn = new BufferedReader(new InputStreamReader( System.in)); while (true) { String stringIn = webSocketIn.readLine(); SendToAll (stringIn); // sendToAll chatter server.sendtoall (stringIn); } * /
}
/** * User offline processing *@param conn
*/
public void userLeave(org.java_websocket.WebSocket conn) {
String user = WebSocketPool.getUserByKey(conn);
boolean b = WebSocketPool.removeUser(conn); // Remove the connection from the connection pool
if (b) {
WebSocketPool.sendMessageToOnlineAllUser(user); // Delete the current user from the list of all online users
String leaveMsg = "[system]" + user + "Offline";
WebSocketPool.sendMessageToOnlineAllUser(leaveMsg); // Send information about the current user to an online user}}/** * User online processing *@param user
* @param conn
*/
public void userJoin(String user, org.java_websocket.WebSocket conn) {
WebSocketPool.sendMessageToOnlineAllUser(user); // Add the current user to the list of all online users
String joinMsg = "[system]" + user + "Online!";
WebSocketPool.sendMessageToOnlineAllUser(joinMsg); // Push the message that the current user is online to all online users
WebSocketPool.addUser(user, conn); // Add the current connection object to the connection pool
WebSocketPool.sendMessageToOnlineUser(conn, WebSocketPool.getOnlineUser().toString()); // Sends a list of current online users to the current connection
}
/** * Sends a message to the specified user *@paramCurrentConnection currentConnection *@paramUser Sends the object *@paramMessage message * /
public void sendMessageToUser(WebSocket currentConnection,String user,String message){
WebSocket conn = WebSocketPool.getWebSocketByUser(user); // Get the online connection of the user who sent the object
if (null! = conn){// Send a message to a specific online user
WebSocketPool.sendMessageToOnlineUser(conn,message);
// Send messages to the current user at the same time
WebSocketPool.sendMessageToOnlineUser(currentConnection,message);
}else {
WebSocketPool.sendMessageToOnlineUser(currentConnection,"["+user+"] user is not online, please send later!");
System.out.println("["+user+"] user is not online, please send later!");
WebSocketPool.sendMessageToOnlineUser(currentConnection,"Number of current online users:"+WebSocketPool.getUserCount()+"There."+WebSocketPool.getOnlineUser()); }}}Copy the code
3.Http sends messages
Create webSocketController.java in the Controller layer
package com.dist.controller;
import com.dist.utils.WebSocketPool;
import org.java_websocket.WebSocket;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/ * * *@author [email protected]
* @data 2019/4/17 14:54
*/
@RestController
@RequestMapping("/WebSocket")
public class WebSocketController {
// Push to all online users
@RequestMapping(value = "v1/sendAllUser", method = RequestMethod.GET)
public void sendAllUser(@RequestParam String message){
// Push to all online users
WebSocketPool.sendMessageToOnlineAllUser(message);
}
// Push to an online user
@RequestMapping(value = "v1/sendUser", method = RequestMethod.GET)
public void loginWithDevice(@RequestParam String pushObject, @RequestParam String message){
// Push device object
List<String> userlist = null;
if (pushObject == null || "".equals(pushObject)) {
System.out.println("Push object cannot be NUul");
} else {
userlist = new ArrayList<>(Arrays.asList(pushObject.split(",")));
}
for (String user : userlist){
// Check whether the pushed connection object is online according to the user
WebSocket webSocketByUser = WebSocketPool.getWebSocketByUser(user);
if (null! = webSocketByUser){// Push to an online user
WebSocketPool.sendMessageToOnlineUser(webSocketByUser,message);
}else {
// Failed to push the processing module
System.out.println("User ["+user+"> < span style =" box-sizing: border-box! Important; "); }}}}Copy the code
4. Create a startup task
This task automatically starts when the project starts – open the room
TestStarts.java
import com.dist.service.ChatServer;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Component
public class TestStarts implements InitializingBean {
@Override
public void afterPropertiesSet(a) throws Exception {
int port = 8887;
ChatServer server = new ChatServer(port);
server.start();
System.out.println("Project in progress: Room open");
System.out.println("Port number waiting for client access:"+ server.getPort()); }}Copy the code
H5 front-end code:
H5 test page: introduce jquery.js (put it in the same directory)
At present, the data information on the test page is written dead, you can get data in the background and write dynamic
Test Page 1
H5-WebSocket.html
Note: the var wsUri = “ws: / / 129.204.207.127:8887”; TestStarts. Java starts the TestStarts task by default
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>H5-WebSocket Test</title>
<script src="jquery.js"></script>
</head>
<body>
<br name="#" method="post">
<! --YOUR DATA AREA-->
<label id="a">The current user</label>
<select id="loginsel">
<option value="2">Li si</option>
<option value="3">Zhang SAN</option>
<option value="4">The king 2</option>
</select>
<input type="button" value="Connection" id="btnconnection" onclick="connectionAction()"/>
<input type="button" value="Disconnect" id="btndisconnect" onclick="disconnectAction()"/></br></br>
<label id="b">Send object</label>
<select id="sel">
<option value="1" selected>all</option>
<option value="2">Li si</option>
<option value="3">Zhang SAN</option>
<option value="4">The king 2</option>
</select>
<label id="msg">The message to send</label><input type="text" id="message">
<input type="button" id="btnsendMessage" value="Send message" onclick="sendMessageAction()">
</form>
<script language="javascript"type="text/javascript">
var wsUri =Ws: / / 129.204.207.127:8887 "";
var output;
var message;
var userToMessage;
var websocket;
function connectionAction() {
output = document.getElementById("output");
/ / the websocket room
websocket = new WebSocket(wsUri);
// Open the connection
websocket.onopen = function(evt) {
var loginuser = $('#loginsel option:selected').text();
websocket.send(loginuser);
};
websocket.onmessage = function(evt) {
onMessage(evt)
};
websocket.onerror = function(evt) {
onError(evt)
};
$("#loginsel").attr("disabled"."disabled");
$("#btnconnection").attr("disabled"."disabled");
$("#btndisconnect").removeAttr("disabled");
$("#sel").removeAttr("disabled");
$("#msg").removeAttr("disabled");
$("#btnsendMessage").removeAttr("disabled");
}
// Send a message to the specified user
function sendMessageAction() {
var sendTouser = $('#sel option:selected').text();
message =document.getElementById("message").value;
userToMessage = sendTouser +"@"+message;
websocket.send(userToMessage);
}
// Disconnect the connection
function disconnectAction() {
websocket.close();
writeToScreen("You are disconnected");
$("#loginsel").removeAttr("disabled");
$("#btnconnection").removeAttr("disabled");
$("#btndisconnect").attr("disabled"."disabled");
$("#sel").attr("disabled"."disabled");
$("#msg").attr("disabled"."disabled");
$("#btnsendMessage").attr("disabled"."disabled");
}
/* function init() { output = document.getElementById("output"); testWebSocket(); } function testWebSocket() { websocket = new WebSocket(wsUri); websocket.onopen = function(evt) { onOpen(evt) }; websocket.onmessage = function(evt) { onMessage(evt) }; websocket.onerror = function(evt) { onError(evt) }; websocket.onclose = function(evt) { onClose(evt) }; } * /
function onOpen(evt) {
writeToScreen("CONNECTED");
doSend("Zhansna");
}
function onClose(evt) {
writeToScreen("You are disconnected");
websocket.close();
}
// Receive the message
function onMessage(evt) {
writeToScreen('RESPONSE: '+ evt.data+'</span>');
}
function onError(evt) {
writeToScreen('ERROR: '+ evt.data);
}
function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<h2>WebSocket Test</h2>
<div id="output"></div>
</body>
</html>
Copy the code
Test page 2
H5-WebSocket2.html
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>H5-WebSocket Test2</title>
<script src="jquery.js"></script>
</head>
<body>
<br name="#" method="post">
<! --YOUR DATA AREA-->
<label id="a">The current user</label>
<select id="loginsel">
<option value="2">Li si</option>
<option value="3">Zhang SAN</option>
<option value="4">The king 2</option>
</select>
<input type="button" value="Connection" id="btnconnection" onclick="connectionAction()"/>
<input type="button" value="Disconnect" id="btndisconnect" onclick="disconnectAction()"/></br></br>
<label id="b">Send object</label>
<select id="sel">
<option value="1" selected>all</option>
<option value="2">Li si</option>
<option value="3">Zhang SAN</option>
<option value="4">The king 2</option>
</select>
<label id="msg">The message to send</label><input type="text" id="message">
<input type="button" id="btnsendMessage" value="Send message" onclick="sendMessageAction()">
</form>
<script language="javascript"type="text/javascript">
var wsUri =Ws: / / 129.204.207.127:8887 "";
var output;
var message;
var userToMessage;
var websocket;
function connectionAction() {
output = document.getElementById("output");
/ / the websocket room
websocket = new WebSocket(wsUri);
// Open the connection
websocket.onopen = function(evt) {
var loginuser = $('#loginsel option:selected').text();
websocket.send(loginuser);
};
websocket.onmessage = function(evt) {
onMessage(evt)
};
websocket.onerror = function(evt) {
onError(evt)
};
$("#loginsel").attr("disabled"."disabled");
$("#btnconnection").attr("disabled"."disabled");
$("#btndisconnect").removeAttr("disabled");
$("#sel").removeAttr("disabled");
$("#msg").removeAttr("disabled");
$("#btnsendMessage").removeAttr("disabled");
}
// Send a message to the specified user
function sendMessageAction() {
var sendTouser = $('#sel option:selected').text();
message =document.getElementById("message").value;
userToMessage = sendTouser +"@"+message;
websocket.send(userToMessage);
}
// Disconnect the connection
function disconnectAction() {
websocket.close();
writeToScreen("You are disconnected");
$("#loginsel").removeAttr("disabled");
$("#btnconnection").removeAttr("disabled");
$("#btndisconnect").attr("disabled"."disabled");
$("#sel").attr("disabled"."disabled");
$("#msg").attr("disabled"."disabled");
$("#btnsendMessage").attr("disabled"."disabled");
}
/* function init() { output = document.getElementById("output"); testWebSocket(); } function testWebSocket() { websocket = new WebSocket(wsUri); websocket.onopen = function(evt) { onOpen(evt) }; websocket.onmessage = function(evt) { onMessage(evt) }; websocket.onerror = function(evt) { onError(evt) }; websocket.onclose = function(evt) { onClose(evt) }; } * /
function onOpen(evt) {
writeToScreen("CONNECTED");
doSend("Zhansna");
}
function onClose(evt) {
writeToScreen("You are disconnected");
websocket.close();
}
// Receive the message
function onMessage(evt) {
writeToScreen('RESPONSE: '+ evt.data+'</span>');
}
function onError(evt) {
writeToScreen('ERROR: '+ evt.data);
}
function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<h2>WebSocket Test2</h2>
<div id="output"></div>
</body>
</html>
Copy the code
H5 pages can now communicate with each other. This is just an H5 test case, and it is also true in a real project, but depending on the requirements of the project, the code logic. My project is the timely push of version push and feedback messages;
Andorid test code:
The best way to test is to create a blank Andorid app
Java-websocket dependencies are introduced in. Gradle
dependencies{
implementation 'org. Java - websocket: Java - websocket: 1.3.0'
}
Copy the code
Page code
activity_main.xml
<?xml version="1.0" encoding="utf-8"? >
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
>
<ScrollView
android:id="@+id/svChat"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Spinner
android:id="@+id/spDraft"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<! Ws: / / 192.168.1.104, : 80 / JSR356 - WebSocket WebSocket / -- -- >
<! Ws: / / 192.168.1.104, : 8887 - >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/etAddress"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4" />
<Spinner
android:id="@+id/spAddress"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<! -- Select login user -->
<EditText
android:id="@+id/etloginName"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4"
android:hint="Select login name" /><! --Jack-->
<Spinner
android:id="@+id/sploginName"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
</LinearLayout>
<Button
android:id="@+id/btnConnect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connection" />
<Button
android:id="@+id/btnClose"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Disconnect" />
<EditText
android:id="@+id/etDetails"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@null"
android:focusable="false"
android:focusableInTouchMode="false"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textSize="13dp" />
<Button
android:id="@+id/btnClearDetails"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Clear chat history" />
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Spinner
android:id="@+id/spName"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"/>
<! --<EditText android:id="@+id/etName" android:layout_width="wrap_content" android:layout_height="match_parent" Android :hint=" "Android :layout_weight="1"/>--><! --Jack-->
<EditText
android:id="@+id/etMessage"
android:layout_width="0dp"
android:layout_height="match_parent"
android:hint="Send message content"
android:layout_weight="4"/>
<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Send"/>
</LinearLayout>
</LinearLayout>
Copy the code
Logic code
MainActivity.java
package com.dist.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Spinner;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_10;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.drafts.Draft_75;
import org.java_websocket.drafts.Draft_76;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ScrollView svChat;
private Spinner spDraft;
private EditText etAddress;
private Spinner spAddress;
private Spinner sploginName;
private EditText etloginName;
private Button btnConnect;
private Button btnClose;
private EditText etDetails;
private Button btnClearDetails;
private Spinner spName;
//private EditText etName;
private EditText etMessage;
private Button btnSend;
private WebSocketClient client;// Connect to the client
private DraftInfo selectDraft;// Connection protocol
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
svChat = (ScrollView) findViewById(R.id.svChat);
spDraft = (Spinner) findViewById(R.id.spDraft);
etAddress = (EditText) findViewById(R.id.etAddress);
spAddress = (Spinner) findViewById(R.id.spAddress);
sploginName = (Spinner) findViewById(R.id.sploginName);
etloginName = (EditText) findViewById(R.id.etloginName);
btnConnect = (Button) findViewById(R.id.btnConnect);
btnClose = (Button) findViewById(R.id.btnClose);
etDetails = (EditText) findViewById(R.id.etDetails);
btnClearDetails = (Button) findViewById(R.id.btnClearDetails);
spName = (Spinner) findViewById(R.id.spName);
//etName = (EditText) findViewById(R.id.etName);
etMessage = (EditText) findViewById(R.id.etMessage);
btnSend = (Button) findViewById(R.id.btnSend);
DraftInfo[] draftInfos = {new DraftInfo("The WebSocket protocol Draft_17".new Draft_17()), new DraftInfo
("The WebSocket protocol Draft_10".new Draft_10()), new DraftInfo("The WebSocket protocol Draft_76".new Draft_76()), new
DraftInfo("The WebSocket protocol Draft_75".new Draft_75())};// All connection protocols
selectDraft = draftInfos[0];// The first connection protocol is selected by default
ArrayAdapter<DraftInfo> draftAdapter = new ArrayAdapter<DraftInfo>(this, android.R.layout
.simple_spinner_item, draftInfos);
spDraft.setAdapter(draftAdapter);
spDraft.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<? > parent, View view,int position, long id) {
selectDraft = (DraftInfo) spDraft.getItemAtPosition(position);// Select the connection protocol
etDetails.append("Current connection protocol:" + selectDraft.draftName + "\n");
Log.e("wlf"."Select connection protocol:" + selectDraft.draftName);
}
@Override
public void onNothingSelected(AdapterView
parent) {
selectDraft = null;/ / to empty
Log.e("wlf"."No connection protocol selected"); }}); ServerInfo[] serverInfos = {new ServerInfo("Connecting to the Intranet Web Background".Ws: / / 192.168.2.114:8887 ""),new ServerInfo("Connect to extranet Web Background"."Ws: / / 129.204... : 8887")};// All connections to the background // external network to the server
etAddress.setText(serverInfos[0].serverAddress);// The first connection protocol is selected by default
ArrayAdapter<ServerInfo> serverAdapter = new ArrayAdapter<ServerInfo>(this, android.R.layout
.simple_spinner_item, serverInfos);
spAddress.setAdapter(serverAdapter);
spAddress.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<? > parent, View view,int position, long id) {
ServerInfo selectServerInfo = (ServerInfo) spAddress.getItemAtPosition(position);// Select connect background
etAddress.setText(selectServerInfo.serverAddress);
etDetails.append("Currently connected background:" + selectServerInfo.serverName + "\n");
Log.e("wlf"."Currently connected background:" + selectServerInfo.serverName);
}
@Override
public void onNothingSelected(AdapterView
parent) {
selectDraft = null;/ / to empty
Log.e("wlf"."No connection background selected"); }}); UserNameInfo[] loginNameInfo = {new UserNameInfo("Dumbledore." "."Dumbledore." "), new UserNameInfo("LaoZheng"."LaoZheng"),new UserNameInfo("Little Goldfish"."Little Goldfish"),
new UserNameInfo("Zhang"."Zhang"),new UserNameInfo("Bill"."Bill"),new UserNameInfo("Two"."Two")};// Login object
etloginName.setText(loginNameInfo[0].name);// The first user is selected by default
ArrayAdapter<UserNameInfo> loginNameAdapter = new ArrayAdapter<UserNameInfo>(this, android.R.layout
.simple_spinner_item, loginNameInfo);
sploginName.setAdapter(loginNameAdapter);
sploginName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<? > parent, View view,int position, long id) {
UserNameInfo selectloginNameInfo = (UserNameInfo) sploginName.getItemAtPosition(position);// Select connect background
etloginName.setText(selectloginNameInfo.name);
etDetails.append("Current login user name:" + selectloginNameInfo.loginName + "\n");
Log.e("wlf"."Current login user name:" + selectloginNameInfo.loginName);
}
@Override
public void onNothingSelected(AdapterView
parent) {
etloginName = null;/ / to empty
Log.e("wlf"."No login object selected"); }}); UserNameInfo[] userNameInfo = {new UserNameInfo("all"."all"),new UserNameInfo("Dumbledore." "."Dumbledore." "), new UserNameInfo("LaoZheng"."LaoZheng"),new UserNameInfo("Little Goldfish"."Little Goldfish"),
new UserNameInfo("Bill"."Bill"), new UserNameInfo("Zhang"."Zhang"), new UserNameInfo("Two"."Two")};// The object to send
ArrayAdapter<UserNameInfo> userNameAdapter = new ArrayAdapter<UserNameInfo>(this, android.R.layout
.simple_spinner_item, userNameInfo);
spName.setAdapter(userNameAdapter);
spName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<? > parent, View view,int position, long id) {
UserNameInfo selectuserNameInfo = (UserNameInfo) spName.getItemAtPosition(position);// Select connect background
// etName.setText(selectuserNameInfo.name);
etDetails.append("Send object:" + selectuserNameInfo.loginName + "\n");
Log.e("wlf"."Send object:" + selectuserNameInfo.loginName);
}
@Override
public void onNothingSelected(AdapterView
parent) {
// etName = null; / / to empty
Log.e("wlf"."No send object selected"); }}); btnConnect.setOnClickListener(this);
btnClearDetails.setOnClickListener(this);
btnClose.setOnClickListener(this);
btnSend.setOnClickListener(this);
WebSocketImpl.DEBUG = true;
System.setProperty("java.net.preferIPv6Addresses"."false");
System.setProperty("java.net.preferIPv4Stack"."true");
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnConnect:
try {
if (selectDraft == null) {
return;
}
if(etloginName == null) {return;
}
String address = etAddress.getText().toString().trim();
if (address.contains("JSR356-WebSocket")) {
//address += etName.getText().toString().trim();
}
Log.e("wlf"."Connection address:" + address);
client = new WebSocketClient(new URI(address), selectDraft.draft) {
@Override
public void onOpen(final ServerHandshake serverHandshakeData) {
runOnUiThread(new Runnable() {
@Override
public void run(a) {
etDetails.append("Already connected to the server [" + getURI() + "】 \ n");
Log.e("wlf"."Already connected to the server [" + getURI() + "】");
spDraft.setEnabled(false);
etAddress.setEnabled(false);
spAddress.setEnabled(false);
etloginName.setEnabled(false);
sploginName.setEnabled(false);
btnConnect.setEnabled(false);
//etName.setEnabled(false);
spName.setEnabled(true);
btnClearDetails.setEnabled(true);
btnClose.setEnabled(true);
btnSend.setEnabled(true); }}); }@Override
public void onMessage(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run(a) {
etDetails.append("Get server info [" + message + "】 \ n");
Log.e("wlf"."Get server info [" + message + "】"); }}); }@Override
public void onClose(final int code, final String reason, final boolean remote) {
runOnUiThread(new Runnable() {
@Override
public void run(a) {
etDetails.append("Disconnect from the server [" + getURI() + ", status code:" + code + ", disconnect reason:" + reason +
"】 \ n");
Log.e("wlf"."Disconnect from the server [" + getURI() + ", status code:" + code + ", disconnect reason:" + reason + "】");
spDraft.setEnabled(true);
etAddress.setEnabled(true);
spAddress.setEnabled(true);
etloginName.setEnabled(true);
sploginName.setEnabled(true);
btnConnect.setEnabled(true);
//etName.setEnabled(true);
spName.setEnabled(false);
btnClearDetails.setEnabled(true);
btnClose.setEnabled(false);
btnSend.setEnabled(false); }}); }@Override
public void onError(final Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run(a) {
etDetails.append("The connection is abnormal." + e + "】 \ n");
Log.e("wlf"."The connection is abnormal." + e + "】");
spDraft.setEnabled(true);
etAddress.setEnabled(true);
btnConnect.setEnabled(true);
//etName.setEnabled(true);
btnClearDetails.setEnabled(false);
btnClose.setEnabled(false);
btnSend.setEnabled(false); }}); }}; client.connect();new Thread(){
@Override
public void run(a){
super.run();
try {
Thread.sleep(200);
if(client ! =null) {
client.send(etloginName.getText().toString().trim());
svChat.post(new Runnable() {
@Override
public void run(a) {
svChat.fullScroll(View.FOCUS_DOWN);
etMessage.setText(""); etMessage.requestFocus(); }}); }}catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
} catch (Exception e) {
e.printStackTrace();
}
break;
case R.id.btnClearDetails:
if(etDetails.getText().toString() ! =null && etDetails.getText().length()>0) {
etDetails.setText("");
}
break;
case R.id.btnClose:
if(client ! =null) {
client.close();
}
break;
case R.id.btnSend:
try {
if(client ! =null) {
//client.send(etname.gettext ().toString().trim()) + ":" + etmessage.gettext ().toString().trim());
//client.send(etName.getText().toString().trim() +"@"+etMessage.getText().toString().trim());
client.send(spName.getSelectedItem().toString().trim() +"@"+etMessage.getText().toString().trim());
svChat.post(new Runnable() {
@Override
public void run(a) {
svChat.fullScroll(View.FOCUS_DOWN);
etMessage.setText(""); etMessage.requestFocus(); }}); }}catch (Exception e) {
e.printStackTrace();
}
break; }}@Override
protected void onDestroy(a) {
super.onDestroy();
if(client ! =null) { client.close(); }}private class DraftInfo {
private final String draftName;
private final Draft draft;
public DraftInfo(String draftName, Draft draft) {
this.draftName = draftName;
this.draft = draft;
}
@Override
public String toString(a) {
returndraftName; }}private class ServerInfo {
private final String serverName;
private final String serverAddress;
public ServerInfo(String serverName, String serverAddress) {
this.serverName = serverName;
this.serverAddress = serverAddress;
}
@Override
public String toString(a) {
returnserverName; }}private class UserNameInfo {
private final String loginName;
private final String name;
public UserNameInfo(String loginName, String name) {
this.loginName = loginName;
this.name = name;
}
@Override
public String toString(a) {
returnloginName; }}}Copy the code
H5 now communicates with Andorid