hikalkan / scs Goto Github PK
View Code? Open in Web Editor NEWTCP Server/Client Communication and RMI Framework
License: MIT License
TCP Server/Client Communication and RMI Framework
License: MIT License
why always is needed to use
private static void WriteInt32(byte[] buffer, int startIndex, int number)
{
buffer[startIndex] = (byte)((number >> 24) & 0xFF);
buffer[startIndex + 1] = (byte)((number >> 16) & 0xFF);
buffer[startIndex + 2] = (byte)((number >> 8) & 0xFF);
buffer[startIndex + 3] = (byte)((number) & 0xFF);
}
because of that offset you did soft hard to work wit any other languages.
If you made serwer side with your scs lib and client side with java. And you are using simple txt message you must remember to transform every command by that function because simple you will get Exception because:
var messageLength = ReadInt32(_receiveMemoryStream);
if (messageLength > MaxMessageLength) //That will be true
I'v made some solution for that soft can be compatible with java.
private static void WriteInt32(byte[] buffer, int startIndex, int number)
{
buffer[startIndex] = (byte)((number >> 24) & 0xFF);
buffer[startIndex + 1] = (byte)((number >> 16) & 0xFF);
buffer[startIndex + 2] = (byte)((number >> 8) & 0xFF);
buffer[startIndex + 3] = (byte)((number) & 0xFF);
}
public static byte[] GetBytes(String message) throws UnsupportedEncodingException {
byte[] serializedMessage = message.getBytes("UTF-8");
int messageLength = serializedMessage.length;
//Create a byte array including the length of the message (4 bytes) and serialized message content
byte[] bytes = new byte[messageLength + 4];
WriteInt32(bytes, 0, messageLength);
System.arraycopy(serializedMessage, 0, bytes, 4, messageLength);
return bytes;
}
and use it like that:
String str = "asdsa\n";
byte[] b = GetBytes(str);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.write(b, 0, b.length);
Hi,
We have a logging service hosted in our infrastructure, that is built using HIK SCS library.
Is it possible to connect to the service normally without HIK SCS client?
I am getting issues.
Hello Halil. I think I found a possible bug in the TcpCommunicationChannel SendMessageInternal class method.
The method begins with
// Send message
totalSent var = 0;
lock (_syncLock)
{
.....
totalSent + = sent;
}
The problem I see is that the variable totalSent is out of lock which if you were using several processes other could enter the method, initialize the variable to zero, modifying the value of the same that is used to complete the loop (below ....
totalSent + = sent;
)
I have not tested to confirm it but I think it is possible.
Greetings from Argentina!!
Hi ~
I had some test with your scs about RMI.
The client can request historical data to server then this data size is 13,000 bytes ~ 140,000 bytes almost.
After client request data several times, server memory is increase every time client call method and die.
Did you have a test about this case ?
like this: https://github.com/furesoft/P2P
Did you have a chance to look into SSL to add it to the framework?
Stop and restart server with exception on port 800, other ports are OK:
Stop --> Waiting for _running = false --> Start
20-07 23:05:17 [SERVER] [EXCEPTION][d__9.MoveNext]: DeviceRouteFactory :Only one usage of each socket address (protocol/network address/port) is normally permitted at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.Bind(EndPoint localEP) at System.Net.Sockets.TcpListener.Start(Int32 backlog) at Hik.Communication.Scs.Communication.Channels.Tcp.TcpConnectionListener.StartSocket() in D:\Bitbucket\Adsun-Service-BM\Src\Libs\Scs\Communication\Scs\Communication\Channels\Tcp\TcpConnectionListener.cs:line 74 at Hik.Communication.Scs.Communication.Channels.Tcp.TcpConnectionListener.Start() in D:\Bitbucket\Adsun-Service-BM\Src\Libs\Scs\Communication\Scs\Communication\Channels\Tcp\TcpConnectionListener.cs:line 51 at Hik.Communication.Scs.Server.ScsServerBase.Start() in D:\Bitbucket\Adsun-Service-BM\Src\Libs\Scs\Communication\Scs\Server\ScsServerBase.cs:line 99 at Route.DeviceRoute.DeviceRouteFactory.d__9.MoveNext() in D:\Bitbucket\Adsun-Service-BM\Src\Route\DeviceRoute\DeviceRouteFactory.cs:line 84
Whether to now provide a way for clients to access the domain name to connect to the server?
I don't want to access it directly through an IP address.
example:
var client = ScsServiceClientBuilder.CreateClient<IPhoneBookService>(
new ScsTcpEndPoint("github.com", 10048));
Use it like this.
@hikalkan
thanks.
Does your reconnection mechanism reconnect at intervals specified by ReConnectCheckPeriod and not only if the client loses its connection to the server?Because from the log I printed, it was reconnected at intervals of ReConnectCheckPeriod, which would consume system resources in high concurrency scenarios. Which leads to a decrease in the forwarding rate.My ReConnectCheckPeriod is set to 30 seconds
As the title suggests I am using Scs on a linux server with .NET 5 runtimes. When a connection opens, it immediately closes with a error "Resource temporarily unavailable".
I have fixed this by removing the code around the connection method in TcpHelper.cs which disables Blocking and then re-enables it again right after. This change works now with no noticeable side effects.
Could you explain why Blocking was disabled while connecting? Also could this cause issues later when I test with more connections?
Is it possible to use protobuf for communication?
This is a great idea!
Hey
Is it possible to invoke an mehtod on the client side and return the results to the server? That would save me a whole of a lot of work :)
Are there any examples for this?
Thanks in advance!
Is there a possibilty to encrypt the connection like via SSL? As an alternative I can encrypt the message itselfe but I have to change the encryption key from time to time and it may be a problem if there are clients with different updated versions.
Best wishes
add asynchronus methods like SendMessageAsync
with Task parallel library
ProtoBuf ??
Hello, i am trying to build the code sample to understand the flow in the library.
My Dev Env:
OS: Win7 32 Bit OS
STUDIO: VS 2010
Am getting protobuf library reference issue.
How to solve this ?
Thanks
Ronald
Could you please help me!
How to
1.Need username and password login.
2.Server connect db username and password check.
Sometimes following error occurred when the client is disconnected and then reconnected.
Error: "The nick '" + userInfo.Nick + "' is being used by another user. Please select another one.
Sometimes, server don't know whether client is disconnected or connected.
To solve this issue:
add support to send a file to another client/server, chunk based
can't run on unity. .net 4.5 is version to hight
Hi @hikalkan ,
Is there a difference between static and dynamic linking?
If I add a reference to Scs.dll everything works. But If I include the source in my project directly (the Collections, Communication and Threading directories), then when I try a simple client/server application I get a timeout when the client tries to send a synchronized message!
The timeout happens in the SynchronizedMessenger's ReceiveMessage function and the server never receives the message that the client sent.
Any Ideas?
Thanks,
Matic
Is there any configuration for the server
I deploy application on my web-server the application work smoothly in the local but when i try to access it from the web there is an error
my server IP Address is public and add in bound rule for the port and open it for a public.
is there any extra configuration?
When using ScsServiceBuilder, is there a way to get the service type back on client connection?
I am trying to get what service was connected to returned during the ClientConnected event.
For instance the client connecting to
server.AddService<IPhoneBookService, PhoneBookService>(new PhoneBookService());
The connection evernt should also return they type PhoneBookService's type name
On the sample server I got compilation error when on "e.Client.MessageReceived" saying that "'IScsClientService' does not contains a definition for 'MessageReceived'"...
What am I missing?
static void Server_ClientConnected(object sender, ServerClientEventArgs e)
{
Console.WriteLine("A new client is connected. Client Id = " + e.Client.ClientId);
//Register to MessageReceived event to receive messages from new client
e.Client.MessageReceived += Client_MessageReceived;
}
By the way, very nice piece of software! Congratulations!
I think I've found the reason.
Thank you
Hello once again, are there any plans to update the nuget package?
Hi,
First of all, thanks for your great work on the project!
I'm having an issue with stress testing, when the clients communicate with the server in a parallel way, I would got a AccessViolationException from mscorlib.dll!System.Threading._IOCompletionCallback.PerformIOCompletionCallback.
I'm suspecting it's caused by TcpClient EndReceive method but cannot approve it. The code sample can be found here:
Client App:
class Program
{
static List<string> clients = new List<string>() { };
static void Main()
{
for (int i = 0; i < 1000; i++)
{
clients.Add(i.ToString());
}
Thread worker = new Thread(ThreadTask);
worker.IsBackground = true;
worker.Start();
Console.WriteLine("Press enter to disconnect from server...");
Console.ReadLine(); //Wait user to press enter
}
static void ThreadTask()
{
Parallel.ForEach(clients, c =>
{
new Action(() =>
{
CreateClient(c);
}).Invoke();
});
}
static void CreateClient(string c)
{
while (true)
{
Console.Write(c + ", ");
for (int i = 0; i < 5; i++)
{
//Create a client object to connect a server on 127.0.0.1 (local) IP and listens 10085 TCP port
using (var client = ScsClientFactory.CreateClient(new ScsTcpEndPoint("127.0.0.1", 10085)))
{
try
{
//Create a SynchronizedMessenger that uses the client as internal messenger.
using (var synchronizedMessenger = new SynchronizedMessenger<IScsClient>(client))
{
client.Connect(); //Connect to the server
synchronizedMessenger.Start(); //Start synchronized messenger messenger
var messageText = "MESSAGE FROM CLIENT:" + c; //Get a message from user
//Send a message to the server
synchronizedMessenger.SendMessage(new ScsTextMessage(messageText));
//Receive a message from the server
var receivedMessage = synchronizedMessenger.ReceiveMessage<ScsTextMessage>();
Thread.Sleep(200);
synchronizedMessenger.Stop(); //Stop synchronized messenger messenger
Thread.Sleep(200);
client.Disconnect(); //Disconnect to the server
}
}
catch { }
}
Thread.Sleep(1000);
}
Thread.Sleep(5000);
}
}
}
Server App:
class Program
{
static void Main()
{
//Create a server that listens 10085 TCP port for incoming connections
var server = ScsServerFactory.CreateServer(new ScsTcpEndPoint(10085));
//Register events of the server to be informed about clients
server.ClientConnected += Server_ClientConnected;
server.ClientDisconnected += Server_ClientDisconnected;
server.Start(); //Start the server
Console.WriteLine("Server is started successfully. Press enter to stop...");
Console.ReadLine(); //Wait user to press enter
server.Stop(); //Stop the server
}
static void Server_ClientConnected(object sender, ServerClientEventArgs e)
{
Console.WriteLine("A new client is connected. Client Id = " + e.Client.ClientId);
//Register to MessageReceived event to receive messages from new client
e.Client.MessageReceived += Client_MessageReceived;
}
static void Server_ClientDisconnected(object sender, ServerClientEventArgs e)
{
Console.WriteLine("A client is disconnected! Client Id = " + e.Client.ClientId);
}
static void Client_MessageReceived(object sender, MessageEventArgs e)
{
var message = e.Message as ScsTextMessage; //Server only accepts text messages
if (message == null)
{
return;
}
//Get a reference to the client
var client = (IScsServerClient)sender;
Console.WriteLine(message.Text + " FROM CLIENT - " + client.ClientId);
//Send reply message to the client
client.SendMessage(
new ScsTextMessage(
"ACK",
message.MessageId //Set first message's id as replied message id
));
}
}
Please kindly have a test and suggest.
Regards,
Tong
Hello I was wondering why only ip addresses can be used when instantiating clients when hostnames can also be used
Consider to add OnError event.
well done!
I'm just reporting some errors about multithread clients
I'm taking Chat Server as an example
take this function as example:
/// <summary>
/// Sends a public message to room.
/// It will be seen all users in room.
/// </summary>
/// <param name="message">Message to be sent</param>
public void SendMessageToRoom(ChatMessage message)
{
//Get ChatClient object
var senderClient = _clients[CurrentClient.ClientId];
if (senderClient == null)
{
throw new ApplicationException("Can not send message before login.");
}
//Send message to all online users
Task.Factory.StartNew(
() =>
{
foreach (var chatClient in _clients.GetAllItems())
{
try
{
chatClient.ClientProxy.OnMessageToRoom(senderClient.User.Nick, message);
}
catch
{
}
}
});
}
here you call a task that, in the same thread, try to call
chatClient.ClientProxy.OnMessageToRoom(senderClient.User.Nick, message);
this cause that if a client has problems completing the response, stuck all the queue
I've experienced it just launching 2 chat clients and debugging one of them, setting up a breakpoint in the
OnMessageToRoomclient function then sending a message from the other client to the room
while the debugged instance hit the breakpoint, the other client didn't received its sent message and couldn't sent others. as soon as i resumed the paused debugged client, all messages arrived.
I tried to create an inner Task instead of an outer:
foreach (var chatClient in _clients.GetAllItems()) { try { //Send message to all online users Task.Factory.StartNew(() => { chatClient.ClientProxy.OnMessageToRoom(chatRoom, message); }); } catch { } }inside the foreach loop but that helped only partially: i was able to receive first message sent, but then i couldn't send another (interface freeze, so i suppose the server didn't was in some lock state, didn't accepting a new message until the previous one ended to be dispatched
can you explain how to solve this problem and suggest how to fix that? thanks and again, good job on this library!
Could you add proxy support. Socks5?
I found this online maybe it will help?
https://www.codeproject.com/Articles/5954/C-class-for-connecting-via-a-SOCKS5-Proxy-Server
use ClientReConnecter example?
i use sample IrcChatSystem
how to use in sample IrcChatSystem
//Create a reconnecter to reconnect automatically on disconnect.
var reconnecter = new ClientReConnecter(_scsClient) {ReConnectCheckPeriod = 30000};
When a client disconnects whilst waiting in SendMessageAndWaitForResponse then:
Can we bubble up the Disconnected event in SendMessageAndWaitForResponse ?
Lets Say you have Client and Server.
If you merge Client with Scs and CommonLib(ScsService) with some ILMerge tool, then the method execution stops to work. I noticed that the DeserializationAppDomainBinder on server side is trying to find an not existing library. Like it's trying to find Client lib that got merged instead of Scs.dll. Is there way to bypass it?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.