logo
Tags down

shadow

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];
     while(1)
     {
         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
             break;
         }
         //this function does the hard job of knowing what to do with all these data
         processBuffer(ReadBuffer, n);
     }

 close(sockfd);

 }

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);
                                    break;
                                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 };
                                            destinationClient.Context.Channel.WriteAndFlushAsync(clientMessage);
                                        }
                                    }
                                    break;
                            }
                        }
                    }
                }
            }, 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)
        {
            context.Flush();
            base.ChannelReadComplete(context);
        }

        // Automatically stop the message-processing thread when this object is disposed
        public void Dispose()
        {
            cancellation.Cancel();
        }
    }
}
Related Posts Related Posts :
  • Multiple Textbox Validations
  • Access properties of a virtual class in partial class
  • How to post a message to google chat room using C#? (**Error**: Request had insufficient authentication scopes)
  • How to get all USA timezone IDs using nodatime
  • How to pass object of unknown type to function
  • Is it OK to inherit an empty Interface?
  • If I implement IEquatable<T>, will I lose the option to compare by reference?
  • Authorize with both ASP.NET core MVC/Razor site AND a WebAPI
  • If Condition Simplification
  • ASP Net Core Web API: Client side GroupBy is not supported
  • C# I have a DLL file and I need to make a class that inherits from a class that's in the DLL file?
  • How can I cause a derived method to be called during an inherited base constructor?
  • How to subtract between two integer List in C#?
  • Using SerialPort variable through MainWindow
  • The most efficient way (performance/time wise) to find a highest value in a List with continuously changing values?
  • How to Deserialize Json string to Type without creating class
  • How to enforce this one-to-many constraint in C#?
  • MVC: Unable to update one of my model's properties
  • Task.WhenAll with LINQ select
  • I am creating the controller in asp dot net core but Giving Error
  • How to define a constraint in Ortools to set a limit of distinct values
  • How to check for Carriage Return of each element end in string array and add if not exists?
  • Multithreading | Thread was being aborted
  • Why would you use TransactionScope for Read-Only Database Calls in NET C#?
  • How to branch code based on class data type
  • Is there a way to linking two data values, simpler than Dictionary?
  • How to display a file in a folder without showing physical path?
  • Are binary tree nodes passed by reference?
  • Convert float to decimal, wrong value
  • Can someone tell me why (return DayName;) causes an ERROR cause it's an unassigned local variable?
  • Prohibit access to the private variable
  • c# How do I correctly compile code for distribution?
  • C# Passing a reference to a generic method to another method
  • Pass property name as parameter
  • Why converting empty value to datetime2 is throwing conversion error in SQL?
  • Is it possible to have a method that I can call one time with (ref int x) and other times with (value int x) --- (ByValu
  • Why parent task finishes before his children tasks?
  • Ternary Operator behaviour in C#
  • How can I make a c# application outside of visual studio?
  • Why constructors if curl braces
  • Why is MemoryStream not disposed?
  • What is the C# equivalent of Swift's URL struct in Xamarin.iOS?
  • C# importing class as *
  • Find node clicked under context menu
  • Casting: (NewType) vs. Object as NewType
  • Mapping Stream data to data structures in C#
  • Datatable vs Dataset
  • What's the best way to implement BDD/TDD in .NET 2.0?
  • How can I change the background of a masterpage from the code behind of a content page?
  • Developing for ASP.NET-MVC without Visual Studio
  • Most Efficient Way to Test Object Type
  • How to RedirectToAction in ASP.NET MVC without losing request data
  • Locating Text within image
  • Wiggling the mouse
  • .NET Unit Testing packages?
  • Reducing duplicate error handling code in C#?
  • Hiding inherited members
  • How to check for file lock?
  • ViewState invalid only in Safari
  • How do I delete a file which is locked by another process in C#?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org