Skip to content

Commit

Permalink
♻️ client success.
Browse files Browse the repository at this point in the history
  • Loading branch information
crossoverJie committed Apr 24, 2020
1 parent 431138c commit 536d7b3
Show file tree
Hide file tree
Showing 9 changed files with 180 additions and 127 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ nohup java -jar /root/work/route0/cim-forward-route-1.0.0-SNAPSHOT.jar --app.zk
```shell
cp /cim/cim-client/target/cim-client-1.0.0-SNAPSHOT.jar /xx/work/route0/
cd /xx/work/route0/
java -jar cim-client-1.0.0-SNAPSHOT.jar --server.port=8084 --cim.user.id=唯一客户端ID --cim.user.userName=用户名 --cim.group.route.request.url=http://路由服务器:8083/groupRoute --cim.server.route.request.url=http://路由服务器:8083/login
java -jar cim-client-1.0.0-SNAPSHOT.jar --server.port=8084 --cim.user.id=唯一客户端ID --cim.user.userName=用户名 --cim.route.url=http://路由服务器:8083/
```

![](https://ws2.sinaimg.cn/large/006tNbRwly1fylgxjgshfj31vo04m7p9.jpg)
Expand Down Expand Up @@ -167,7 +167,7 @@ curl -X POST --header 'Content-Type: application/json' --header 'Accept: applica
# 启动本地客户端
cp /cim/cim-client/target/cim-client-1.0.0-SNAPSHOT.jar /xx/work/route0/
cd /xx/work/route0/
java -jar cim-client-1.0.0-SNAPSHOT.jar --server.port=8084 --cim.user.id=上方返回的userId --cim.user.userName=用户名 --cim.group.route.request.url=http://路由服务器:8083/groupRoute --cim.server.route.request.url=http://路由服务器:8083/login
java -jar cim-client-1.0.0-SNAPSHOT.jar --server.port=8084 --cim.user.id=上方返回的userId --cim.user.userName=用户名 --cim.route.url=http://路由服务器:8083/
```

## 客户端内置命令
Expand Down
5 changes: 5 additions & 0 deletions cim-client/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@
<version>5.0.0</version>
</dependency>

<dependency>
<groupId>com.crossoverjie.netty</groupId>
<artifactId>cim-rout-api</artifactId>
</dependency>

</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.crossoverjie.cim.client.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crossoverjie.cim.client.config.AppConfiguration;
import com.crossoverjie.cim.client.service.EchoService;
import com.crossoverjie.cim.client.service.RouteRequest;
Expand All @@ -11,17 +10,20 @@
import com.crossoverjie.cim.client.vo.req.P2PReqVO;
import com.crossoverjie.cim.client.vo.res.CIMServerResVO;
import com.crossoverjie.cim.client.vo.res.OnlineUsersResVO;
import com.crossoverjie.cim.common.core.proxy.ProxyManager;
import com.crossoverjie.cim.common.enums.StatusEnum;
import com.crossoverjie.cim.common.exception.CIMException;
import com.crossoverjie.cim.common.res.BaseResponse;
import okhttp3.*;
import com.crossoverjie.cim.route.api.RouteApi;
import com.crossoverjie.cim.route.api.vo.req.ChatReqVO;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
Expand All @@ -39,19 +41,8 @@ public class RouteRequestImpl implements RouteRequest {
@Autowired
private OkHttpClient okHttpClient ;

private MediaType mediaType = MediaType.parse("application/json");

@Value("${cim.group.route.request.url}")
private String groupRouteRequestUrl;

@Value("${cim.p2p.route.request.url}")
private String p2pRouteRequestUrl;

@Value("${cim.server.route.request.url}")
private String serverRouteLoginUrl;

@Value("${cim.server.online.user.url}")
private String onlineUserUrl;
@Value("${cim.route.url}")
private String routeUrl ;

@Autowired
private EchoService echoService ;
Expand All @@ -62,81 +53,59 @@ public class RouteRequestImpl implements RouteRequest {

@Override
public void sendGroupMsg(GroupReqVO groupReqVO) throws Exception {

JSONObject jsonObject = new JSONObject();
jsonObject.put("msg",groupReqVO.getMsg());
jsonObject.put("userId",groupReqVO.getUserId());
RequestBody requestBody = RequestBody.create(mediaType,jsonObject.toString());

Request request = new Request.Builder()
.url(groupRouteRequestUrl)
.post(requestBody)
.build();

Response response = okHttpClient.newCall(request).execute() ;
RouteApi routeApi = new ProxyManager<>(RouteApi.class, routeUrl, okHttpClient).getInstance();
ChatReqVO chatReqVO = new ChatReqVO() ;
chatReqVO.setUserId(groupReqVO.getUserId());
chatReqVO.setMsg(groupReqVO.getMsg());
Response response = null;
try {
if (!response.isSuccessful()){
throw new IOException("Unexpected code " + response);
}
response = (Response)routeApi.groupRoute(chatReqVO);
}catch (Exception e){
LOGGER.error("exception",e);
}finally {
response.body().close();
}
}

@Override
public void sendP2PMsg(P2PReqVO p2PReqVO) throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg",p2PReqVO.getMsg());
jsonObject.put("userId",p2PReqVO.getUserId());
jsonObject.put("receiveUserId",p2PReqVO.getReceiveUserId());
RequestBody requestBody = RequestBody.create(mediaType,jsonObject.toString());

Request request = new Request.Builder()
.url(p2pRouteRequestUrl)
.post(requestBody)
.build();

Response response = okHttpClient.newCall(request).execute() ;
if (!response.isSuccessful()){
throw new IOException("Unexpected code " + response);
}
RouteApi routeApi = new ProxyManager<>(RouteApi.class, routeUrl, okHttpClient).getInstance();
com.crossoverjie.cim.route.api.vo.req.P2PReqVO vo = new com.crossoverjie.cim.route.api.vo.req.P2PReqVO() ;
vo.setMsg(p2PReqVO.getMsg());
vo.setReceiveUserId(p2PReqVO.getReceiveUserId());
vo.setUserId(p2PReqVO.getUserId());

ResponseBody body = response.body();
Response response = null;
try {
String json = body.string() ;
response = (Response) routeApi.p2pRoute(vo);
String json = response.body().string() ;
BaseResponse baseResponse = JSON.parseObject(json, BaseResponse.class);

//选择的账号不存在
// account offline.
if (baseResponse.getCode().equals(StatusEnum.OFF_LINE.getCode())){
LOGGER.error(p2PReqVO.getReceiveUserId() + ":" + StatusEnum.OFF_LINE.getMessage());
}

}catch (Exception e){
LOGGER.error("exception",e);
}finally {
body.close();
response.body().close();
}
}

@Override
public CIMServerResVO.ServerInfo getCIMServer(LoginReqVO loginReqVO) throws Exception {

JSONObject jsonObject = new JSONObject();
jsonObject.put("userId",loginReqVO.getUserId());
jsonObject.put("userName",loginReqVO.getUserName());
RequestBody requestBody = RequestBody.create(mediaType,jsonObject.toString());
RouteApi routeApi = new ProxyManager<>(RouteApi.class, routeUrl, okHttpClient).getInstance();
com.crossoverjie.cim.route.api.vo.req.LoginReqVO vo = new com.crossoverjie.cim.route.api.vo.req.LoginReqVO() ;
vo.setUserId(loginReqVO.getUserId());
vo.setUserName(loginReqVO.getUserName());

Request request = new Request.Builder()
.url(serverRouteLoginUrl)
.post(requestBody)
.build();

Response response = okHttpClient.newCall(request).execute() ;
if (!response.isSuccessful()){
throw new IOException("Unexpected code " + response);
}
CIMServerResVO cimServerResVO ;
ResponseBody body = response.body();
Response response = null;
CIMServerResVO cimServerResVO = null;
try {
String json = body.string();
response = (Response) routeApi.login(vo);
String json = response.body().string();
cimServerResVO = JSON.parseObject(json, CIMServerResVO.class);

//重复失败
Expand All @@ -152,61 +121,45 @@ public CIMServerResVO.ServerInfo getCIMServer(LoginReqVO loginReqVO) throws Exce
System.exit(-1);
}

}catch (Exception e){
LOGGER.error("exception",e);
}finally {
body.close();
response.body().close();
}



return cimServerResVO.getDataBody();
}

@Override
public List<OnlineUsersResVO.DataBodyBean> onlineUsers() throws Exception{
RouteApi routeApi = new ProxyManager<>(RouteApi.class, routeUrl, okHttpClient).getInstance();

JSONObject jsonObject = new JSONObject();
RequestBody requestBody = RequestBody.create(mediaType,jsonObject.toString());

Request request = new Request.Builder()
.url(onlineUserUrl)
.post(requestBody)
.build();

Response response = okHttpClient.newCall(request).execute() ;
if (!response.isSuccessful()){
throw new IOException("Unexpected code " + response);
}


ResponseBody body = response.body();
OnlineUsersResVO onlineUsersResVO ;
Response response = null;
OnlineUsersResVO onlineUsersResVO = null;
try {
String json = body.string() ;
response = (Response) routeApi.onlineUser();
String json = response.body().string() ;
onlineUsersResVO = JSON.parseObject(json, OnlineUsersResVO.class);

}catch (Exception e){
LOGGER.error("exception",e);
}finally {
body.close();
response.body().close();
}

return onlineUsersResVO.getDataBody();
}

@Override
public void offLine() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("userId", appConfiguration.getUserId());
jsonObject.put("msg", "offLine");
RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString());

Request request = new Request.Builder()
.url(appConfiguration.getClearRouteUrl())
.post(requestBody)
.build();

RouteApi routeApi = new ProxyManager<>(RouteApi.class, routeUrl, okHttpClient).getInstance();
ChatReqVO vo = new ChatReqVO() ;
vo.setMsg("offLine");
vo.setUserId(appConfiguration.getUserId());
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
} catch (IOException e) {
response = (Response) routeApi.offLine(vo);
} catch (Exception e) {
LOGGER.error("exception",e);
} finally {
response.body().close();
Expand Down
16 changes: 2 additions & 14 deletions cim-client/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,8 @@ cim.msg.logger.path = /opt/logs/cim/
#cim.clear.route.request.url=http://45.78.28.220:8083/offLine

###=======本地模拟======###
# 群发消息
cim.group.route.request.url=http://localhost:8083/groupRoute

# 私聊消息
cim.p2p.route.request.url=http://localhost:8083/p2pRoute

# 登录并获取服务器ip+port
cim.server.route.request.url=http://localhost:8083/login

# 在线用户
cim.server.online.user.url=http://localhost:8083/onlineUser

# 清除路由信息
cim.clear.route.request.url=http://localhost:8083/offLine
# route url suggested that this is Nginx address
cim.route.url = http://localhost:8083/

# 客户端唯一ID
cim.user.id=1586617710861
Expand Down
4 changes: 4 additions & 0 deletions cim-common/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,9 @@
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package com.crossoverjie.cim.common.core.proxy;

import com.alibaba.fastjson.JSONObject;
import com.crossoverjie.cim.common.exception.CIMException;
import com.crossoverjie.cim.common.util.HttpClient;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import static com.crossoverjie.cim.common.enums.StatusEnum.VALIDATION_FAIL;

/**
* Function:
*
* @author crossoverJie
* Date: 2020-04-25 00:18
* @since JDK 1.8
*/
public final class ProxyManager<T> {

private final static Logger LOGGER = LoggerFactory.getLogger(ProxyManager.class);

private Class<T> clazz;

private String url;

private OkHttpClient okHttpClient;

public ProxyManager(Class<T> clazz, String url, OkHttpClient okHttpClient) {
this.clazz = clazz;
this.url = url;
this.okHttpClient = okHttpClient;
}

/**
* Get proxy instance of api.
* @return
*/
public T getInstance() {
return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{clazz}, new ProxyInvocation());
}


private class ProxyInvocation implements InvocationHandler {

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
JSONObject jsonObject = new JSONObject();

if (args != null && args.length > 1) {
throw new CIMException(VALIDATION_FAIL);
}


if (method.getParameterTypes().length > 0){
Object para = args[0];
Class<?> parameterType = method.getParameterTypes()[0];
for (Field field : parameterType.getDeclaredFields()) {
field.setAccessible(true);
jsonObject.put(field.getName(), field.get(para));
}
}
url = url + "/" + method.getName();
return HttpClient.call(okHttpClient, jsonObject.toString(), url);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public enum StatusEnum {
/** 参数校验失败**/
VALIDATION_FAIL("3000", "invalid argument"),
/** 失败 */
FAIL("4000", "失败"),
FAIL("4000", "Failure"),

/** 重复登录 */
REPEAT_LOGIN("5000", "Repeat login, log out an account please!"),
Expand All @@ -30,7 +30,6 @@ public enum StatusEnum {
SERVER_NOT_AVAILABLE("7100", "cim server is not available, please try again later!"),

RECONNECT_FAIL("7200", "Reconnect fail, continue to retry!"),

/** 登录信息不匹配 */
ACCOUNT_NOT_MATCH("9100", "The User information you have used is incorrect!"),

Expand Down
Loading

0 comments on commit 536d7b3

Please sign in to comment.