Skip to content

Commit

Permalink
...
Browse files Browse the repository at this point in the history
  • Loading branch information
tmoonlight committed Apr 22, 2020
1 parent 82c83d4 commit 394029a
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 26 deletions.
12 changes: 7 additions & 5 deletions src/NSmartProxy.ClientRouter/Dispatchers/NSPDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,12 @@ public class NSPDispatcher
private string BaseUrl;
//TODO httpclient的一种解决方案:定时对象
private static HttpClient _client;
private static Timer _timer = new Timer(obj=> {
private static Timer _timer = new Timer(obj =>
{
_client?.Dispose();
_client = null;
});

//_client.Dispose();_client = null

public NSPDispatcher(string baseUrl)
Expand Down Expand Up @@ -78,17 +79,18 @@ public async Task<HttpResult<NSPClientConfig>> GetServerClientConfig(string toke

CookieContainer cookieContainer = new CookieContainer();
Cookie cookie = new Cookie("NSPTK", token);
cookie.Domain = BaseUrl;
cookie.Domain = BaseUrl.Substring(0, BaseUrl.IndexOf(':'));

cookieContainer.Add(cookie); // 加入Cookie
HttpClientHandler httpClientHandler = new HttpClientHandler()
{
CookieContainer = cookieContainer,
AllowAutoRedirect = true,
UseCookies = true
};

HttpClient cookieClient = new HttpClient(httpClientHandler);
var httpmsg = await cookieClient.GetAsync(url).ConfigureAwait(false);
var httpmsg = await cookieClient.GetAsync($"{url}?userid=").ConfigureAwait(false);
var httpstr = await httpmsg.Content.ReadAsStringAsync().ConfigureAwait(false);
return JsonConvert.DeserializeObject<HttpResult<NSPClientConfig>>(httpstr);
}
Expand Down
67 changes: 50 additions & 17 deletions src/NSmartProxy.ClientRouter/Router.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,23 +140,8 @@ public async Task Start(bool AlwaysReconnect = false, Action<ClientModel> comple
var appIdIpPortConfig = ClientConfig.Clients;
int clientId = 0;

//0 获取服务器端口配置
try
{
await InitServerPorts();
}
catch (Exception ex)//出错 重连
{
if (IsStarted == false)
{ StatusChanged(ClientStatus.LoginError, null); return; }
else
{
Logger.Error("获取服务器端口失败:" + ex.Message, ex);

await Task.Delay(Global.ClientReconnectInterval, ONE_LIVE_TOKEN_SRC.Token);
continue;
}
}


//0.5 处理登录/重登录/匿名登录逻辑
try
Expand Down Expand Up @@ -204,7 +189,55 @@ public async Task Start(bool AlwaysReconnect = false, Action<ClientModel> comple
continue;
}
}
//1.获取配置

//0.6 从服务端获取配置
if (ClientConfig.UseServerControl)
{
try
{
var configResult = await ClientDispatcher.GetServerClientConfig(arrangedToken);
if (configResult.State == 1)
{
if (configResult.Data == null)
{
Logger.Info("客户端请求服务端配置,但服务端没有对客户端设置配置,将继续使用客户端配置。");
}
else
{
ClientConfig = configResult.Data;
}
}
else
{
Logger.Error("获取配置失败,远程错误:" + configResult.Msg, null);
}
}
catch (Exception ex)
{
Logger.Error("获取配置失败,本地错误:" + ex.ToString(), null);
}

}

//0 获取服务器端口配置
try
{
await InitServerPorts();
}
catch (Exception ex)//出错 重连
{
if (IsStarted == false)
{ StatusChanged(ClientStatus.LoginError, null); return; }
else
{
Logger.Error("获取服务器端口失败:" + ex.Message, ex);

await Task.Delay(Global.ClientReconnectInterval, ONE_LIVE_TOKEN_SRC.Token);
continue;
}
}

//1.获取服务端分配的端口
ConnectionManager = ServerConnectionManager.Create(clientId);
ConnectionManager.CurrentToken = arrangedToken;
ConnectionManager.ClientGroupConnected += ServerConnnectionManager_ClientGroupConnected;
Expand Down
32 changes: 29 additions & 3 deletions src/NSmartProxy/Extension/HttpServer_APIs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -440,9 +440,15 @@ public bool ValidateUserName(string isEdit, string oldUsername, string newUserNa

[API]
[Secure]
public NSPClientConfig GetServerClientConfig(string userId)
public NSPClientConfig GetServerClientConfig(string userId = null)
{
//var claims = StringUtil.ConvertStringToTokenClaims(HttpContext.Request.Cookies[Global.TOKEN_COOKIE_NAME].Value);
if (String.IsNullOrWhiteSpace(userId))
{
var claims =
StringUtil.ConvertStringToTokenClaims(HttpContext.Request.Cookies[Global.TOKEN_COOKIE_NAME].Value);
userId = claims.UserKey;
}

var config = Dbop.GetConfig(userId)?.ToObject<NSPClientConfig>();
return config;
}
Expand All @@ -451,7 +457,27 @@ public NSPClientConfig GetServerClientConfig(string userId)
[Secure]
public void SetServerClientConfig(string userId, string config)
{
Dbop.SetConfig(userId, config);
NSPClientConfig nspClientConfig = null;
try
{
nspClientConfig = config.ToObject<NSPClientConfig>();
nspClientConfig.UseServerControl = true;
nspClientConfig.ProviderAddress = HttpContext.Request.Url.Host;
nspClientConfig.ProviderWebPort = ServerContext.ServerConfig.WebAPIPort;
// nspClientConfig.ConfigPort = ServerContext.ServerConfig.ConfigPort;
// nspClientConfig.ReversePort = ServerContext.ServerConfig.ReversePort;
}
catch (Exception e)
{
throw new Exception("配置格式不正确。");
}

Dbop.SetConfig(userId, nspClientConfig.ToJsonString());
//重置客户端(给客户端发送重定向请求让客户端主动重启)
//var userid = Dbop.Get(userId)?.ToObject<User>().userId;
//ServerContext.CloseAllSourceByClient(int.Parse(userid));

//ServerContext.CloseAllSourceByClient();
//return new NSPClientConfig();
}

Expand Down
24 changes: 23 additions & 1 deletion src/NSmartProxy/Web/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,11 @@ function expandConfigPanel(userId) {
function setClientConfig() {
var userId = $('#hidUserId').val();
var config = $("#inputConfig").val();
var checkResult = isJSON(config);
if (checkResult!="") {
alert("JSON格式不正确,请检查后重试。\n详细错误: "+checkResult);
return;
}
$.get(basepath +
"SetServerClientConfig?userid=" + userId +
"&config=" +
Expand Down Expand Up @@ -452,4 +457,21 @@ function formatJson(json, options) {
pad += indent;
});
return formatted;
};
}

function isJSON(str) {
if (typeof str == 'string') {
try {
var obj = JSON.parse(str);
if (typeof obj == 'object' && obj) {
return "";
} else {
return "无法转换";
}

} catch (e) {
console.log('error:' + str + '!!!' + e);
return e;
}
}
}

0 comments on commit 394029a

Please sign in to comment.