Tags down


Asynchronous multi-direction server-client communication over the same open socket?

By : DisasterMan
Date : July 27 2020, 03:00 AM
To fix the issue you can do When I needed to write an application with a client-server model where the clients could leave and enter whenever they want, (I assume that's also the case for your application as you use mobile devices) I made sure that the clients send an online message to the server, indicating they were connected and ready to do whatever they needed doing.
at that time the server could send messages back to the client trough the same open connection.
code :

Share : facebook icon twitter icon

Network Communication between a java socket (server) and a C++ socket (client)

By : user1638359
Date : March 29 2020, 07:55 AM
wish of those help Here I put a simple code to connect to a server. It may help you if this is your problem.
code :
void client(const char* server_address, short server_port)
     int     sockfd;
     struct sockaddr_in servaddr;

     sockfd = socket(AF_INET, SOCK_STREAM, 0);

     memset(&servaddr, 0x00, sizeof(servaddr));
     servaddr.sin_family = AF_INET;
     servaddr.sin_port = htons(server_port);
     inet_pton(AF_INET, server_address, &servaddr.sin_addr);

     connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

     //from this point you can start write to the server and wait for its respose

     std::string buffer = "testquery";
     writen(sockfd, buffer.c_str(), buffer.length());

     char *ReadBuffer[512];
         memset(ReadBuffer, 0x00, sizeof(ReadBuffer));
         int n = readn(sockfd, ReadBuffer, sizeof(ReadBuffer));
         if(n <= 0)
             //or you dont have anything to read, or you have a problem
         //this function does the hard job of knowing what to do with all these data
         processBuffer(ReadBuffer, n);



Java socket server, C# socket client, communication problems?

By : user1745685
Date : March 29 2020, 07:55 AM
it helps some times The first thing I notice is that you're trying to read a Unicode string directly from a stream. This is problematic for two reasons.
UTF characters are two bytes so calling a read when you have an odd number of bytes in your buffer is either going to block or just cause garbage to come out. Neither one is preferable. When you convert your string to bytes in C# and send them off there's no header specifying the length of the data nor is there a terminator character specified so there's no way to tell at the receiving end (Java in this case) if the string is complete.

Java socket server, PHP socket client; communication works, however PHP 'echoes' data only after the socket connection i

By : jihad
Date : March 29 2020, 07:55 AM
like below fixes the issue Your script works okay, and has no big flaws for what you're looking for. Since you obtain the desired result when you run the script from command line rather than a web browser, we can pinpoint the cause of the issue: the HTTP protocol
HTTP isn't made for sustained connections (like you're used to with Java sockets) but it's simplified workflow is based along the lines of Request/Elaborate/Response/Forget. Therefore, you can't have a "live chat" with a pure HTML/PHP over HTTP solution.

Java Socket: Client-server communication is stuck with multi-threading if more than 1 client

By : user3130024
Date : March 29 2020, 07:55 AM
This might help you There is an obvious problem right here: sending data to sendThreads[i] instead of sendThreads[j]. j is the loop variable, and actually I wanted to use it but mistyped it. But the comments after \\ TODO is correct! That's why it was working without using additional threads. And nothing strange here as stated in the question!
So ServerMain class should be (only the part that should be modified):
code :
// sending received data to other clients except the one from which data has been received
// (so that all clients can receive other clients' data indirectly via this server)
for (int j = 0; j < i; j++) {
    sendThreads[j].send(receivedChar);  // instead of sendThreads[i]
    //Common.send(sendStreams[j], receivedChar);
for (int j = i + 1; j < Common.totalClients; j++) {
    sendThreads[j].send(receivedChar);  // instead of sendThreads[i]
    //Common.send(sendStreams[j], receivedChar);

Asynchronous Socket Server in C#, client to client communication through socket server

By : Stoefff
Date : March 29 2020, 07:55 AM
hope this fix your issue For any complex socket-based application, I would recommend using a socket library like DotNetty to abstract the transport layer and allow you to focus on your application logic. Check out their SecureChat example, it may be pretty similar to what you're trying to achieve.
I've thrown together a quick example of a DotNetty server that would allow you to send commands between clients by having the clients register with the server, and then having the server route messages between the clients.
code :
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using DotNetty.Transport.Channels;
using Newtonsoft.Json;
using System.IO;

namespace MultiClientSocketExample
    public enum Command
        Register = 1,  // Register a new client
        SendToClient = 2, // Send a message from one client to antoher
        DoClientAction = 3 // Replace this with your client-to-client command

    // Envelope for all messages handled by the server
    public class Message
        public string ClientId { get; set; }
        public Command Command { get; set; }
        public string Data { get; set; }

    // Command for seding a message from one client to antoher.   
    // This would be serialized as JSON and stored in the 'Data' member of the Message object.
    public class SendToClientCommand
        public string DestinationClientId { get; set; }  // The client to receive the message

        public Command ClientCommand { get; set; } // The command for the destination client to execute

        public string Data { get; set; } // The payload for the destination client

    // An object for storing unhandled messages in a queue to be processed asynchronously
    // This allows us to process messages and respond to the appropriate client,
    // without having to do everything in the ChannelRead0 method and block the main thread
    public class UnhandledMessage
        private readonly Message message;
        private readonly IChannelHandlerContext context;

        public UnhandledMessage(Message message, IChannelHandlerContext context)
            this.message = message;
            this.context = context;

        public Message Message => message;
        public IChannelHandlerContext Context => context;

        public Command Command => message.Command;
        public string ClientId => message.ClientId;
        public string Data => message.Data;

    // A representation of the connected Clients on the server.  
    // Note:  This is not the 'Client' class that would be used to communicate with the server.
    public class Client
        private readonly string clientId;
        private readonly IChannelHandlerContext context;

        public Client(string clientId, IChannelHandlerContext context)
            this.clientId = clientId;
            this.context = context;

        public string ClientId => clientId;
        public IChannelHandlerContext Context => context;

    // The socket server, using DotNetty's SimpleChannelInboundHandler
    // The ChannelRead0 method is called for each Message received
    public class Server : SimpleChannelInboundHandler<Message>, IDisposable
        private readonly ConcurrentDictionary<string, Client> clients;
        private readonly ConcurrentQueue<UnhandledMessage> unhandledMessages;
        private readonly CancellationTokenSource cancellation;
        private readonly AutoResetEvent newMessage;

        public Server(CancellationToken cancellation)
            this.clients = new ConcurrentDictionary<string, Client>();
            this.newMessage = new AutoResetEvent(false);
            this.cancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellation);

        // The start method should be called when the server is bound to a port.
        // Messages will be received, but will not be processed unless/until the Start method is called
        public Task Start()
            // Start a dedicated thread to process messages so that the ChannelRead operation does not block
            return Task.Run(() =>
                var serializer = JsonSerializer.CreateDefault();  // This will be used to deserialize the Data member of the messages

                while (!cancellation.IsCancellationRequested)
                    UnhandledMessage message;
                    var messageEnqueued = newMessage.WaitOne(100);  // Sleep until a new message arrives

                    while (unhandledMessages.TryDequeue(out message))  // Process each message in the queue, then sleep until new messages arrive
                        if (message != null)
                            // Note: This part could be sent to the thread pool if you want to process messages in parallel
                            switch (message.Command)
                                case Command.Register:
                                    // Register a new client, or update an existing client with a new Context
                                    var client = new Client(message.ClientId, message.Context);
                                    clients.AddOrUpdate(message.ClientId, client, (_,__) => client);
                                case Command.SendToClient:
                                    Client destinationClient;
                                    using (var reader = new JsonTextReader(new StringReader(message.Data)))
                                        var sendToClientCommand = serializer.Deserialize<SendToClientCommand>(reader);
                                        if (clients.TryGetValue(sendToClientCommand.DestinationClientId, out destinationClient))
                                            var clientMessage = new Message { ClientId = message.ClientId, Command = sendToClientCommand.ClientCommand, Data = sendToClientCommand.Data };
            }, cancellation.Token);

        // Receive each message from the clients and enqueue them to be procesed by the dedicated thread
        protected override void ChannelRead0(IChannelHandlerContext context, Message message)
            unhandledMessages.Enqueue(new UnhandledMessage(message, context));
            newMessage.Set(); // Trigger an event so that the thread processing messages wakes up when a new message arrives

        // Flush the channel once the Read operation has completed
        public override void ChannelReadComplete(IChannelHandlerContext context)

        // Automatically stop the message-processing thread when this object is disposed
        public void Dispose()
Related Posts Related Posts :
  • How to check whether string contains specific string in c#
  • UPnP hole punching can't use external IP to access device on local subnet
  • Is there a way to use a conditional when declaring method variables?
  • c# interop Excel - disable or remove automatic page breaks
  • How can I read in these commands from a file using?
  • Pinch and rotate around a point using MRTK and Hololens 1
  • Enhance performance to paint image, is SIMD perhapse a solution?
  • Which one has better performance, data types .NET or alias name data types C#?
  • HttpClient GetAsync taking ~2 seconds
  • linq fastest where method
  • Why can I read more than 254 characters with Console.ReadLine when the docs suggest that I shouldn't be able to?
  • C# - Delayed execution for a collection of items
  • How to display images in a CollectionView from a Base64 string?
  • Convert class object to class index
  • c# identifier expected in controller
  • Subscribe to multiple Observables and gets notified on the same thread
  • how to create windows service using crud operations in c# asp.net
  • Iterating through list of values in a dictionary c#
  • How to Implement Expo.io Push Notifications Send Through C#
  • Gridview columns not being set to width I enter
  • Impersonate User with Forms Authorization
  • ASP.NET MVC Impersonate not working with Forms Authentication
  • Found a potential bug in Moq library while selecting a constructor
  • I want to show a list but page is empty
  • Can this kind of concurrency problem be solved with async/await?
  • Yield keyword giving unexpected values for IEnumerable
  • Many DLLs in System namespace are included when installing library via Nuget
  • C# - range for textbox inputs
  • the Console.ReadLine() Doesn't set the string as the user input
  • Get notified when a variable changed
  • How to list players in room in Photon?
  • Link compile-time created resources to a class library
  • How to quickly choose numbers and weights in such a way as to obtain a specific weighted sum?
  • Downgrade .Net Core project from 3.1 to 2.2 - The type or namespace name 'IWebHostEnvironment' could not be found
  • c# multiplying array elements using system.numerics
  • Private methods vs local functions
  • C# project wants .NET 4.7.1 but I can't install it
  • Binding to object itself, doesn't update when individual property changes
  • remove duplicate from list in object c#
  • JSON.NET - find JObject by value regex in complex object?
  • Save an unknown sized array from unknown string length
  • Camera not centre on player sprite (monogame)
  • How to set a default type for T in a static generic method?
  • How can I insert multiple items of data into SQL using Web API?
  • Finding longest time in an array
  • How to find two quotation marks in a string
  • X509Certificate2 certification issue
  • Image format change in Azure
  • Why is there such big time difference in searching for element with higher index in ConcurrentBag?
  • Async Lambda Issue
  • C# SSIS Script Task - Add Thousand Seperator when formatting Excel column
  • How to check if a textbox starts with numeric value
  • c# Strange Pairs || I can't spot the difference between these 2 solutions?
  • str.Split(".") not working in C# interactive window but work in C# .Net core project?
  • How to do 3 conditions with if else C#
  • merge two lists of same type in c#
  • Blazor - SortBy parameter for table column component
  • InvalidCastException: Specified cast is not valid Error when tried to fetch image from url
  • Search based on Properties
  • Ref string parameter is empty?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org