Multiple clients on socket connection

Hi!
I understand that it is possible that multiple clients listen to one server (on the same port) and even write to it (then it should be a multi-threaded server).
But i would like to refuse connectios, if one client is connected. How can I do that?
In my case I have a (single threaded) server. Now one clients connects. The server waits to receive data from the client and answers, without ever closing the port. that works.
Now if I connect with a second client, the openicng of the socket in the second client works fine, although the server does not seem to notice the second client. Communication is not possible between the server and the second client, and the server doesn't answer to the first client anymore, although he receives data from it.
So, since the server does not seem to notice the second client (does not accept the connection) and I don't get an exception at the second client, what can I do?
Thank you for your help!
concerned Code (if you want to take a look at it):
CLIENT:
socket = new Socket(hostname, echo_port);
SERVER:
try
ServerSocket waitingsocket = new ServerSocket(echo_port);
try
     socket= waitingsocket.accept();
     System.out.println("Client connected");
     ReaderThread reader = new ReaderThread( this, socket );
     reader.start();          
catch (Exception e)
READER:
public void run()
     while (true)
          try {
               int bytesRead = inStream.read(inputBuffer,
               0, inputBuffer.length);
               readCallback.tcpUpdate(inputBuffer,bytesRead);
          catch (Exception oops)
               readCallback.tcpUpdate(null,-1);
          

Just to make sure this is clear: You can NOT have multiple clients on a given socket connection. You CAN have multiple clients connected to a particular port on a given server, but each client will be communicating with the server through a different of socket.
The usual approach here is to set up a listening ServerSocket on the desired port, call accept() on it, then process the communication from the returned Socket object. This is usually done by spawning a new thread and allowing it to handle the socket communication, while the ServerSocket loops around to another accept() for the next communication.
Here's an excellent intro to the concepts (the code is really ugly and poorly implemented, but it does a good job of explaining the overall concept). I used this as a starting point, and now (after a whole lot of development) have a pretty sweet extensible web server class that handles template expansion, etc... (I use this as a quick and dirty UI for some of my apps, instead of requiring the user to install a JSP container):
http://developer.java.sun.com/developer/technicalArticles/Networking/Webserver/
- K

Similar Messages

  • Publishing .fla project including client - server socket connection

    Hi,
    I have designed with Adobe Flash Professional CS5 a .fla project that integrates a client - server connection.
    After publishing it, I have the following issue:
    - when running the generated .exe file for Windows, then the connection to the server works perfectly
    - but when I am running the published .html file, then nothing is sent to the server.
    I have tried to change the Publish Settings.
    When setting the Local Playback Security in Flash menu to "Access network only" instead of "Access local files only" then the last packet that was send using the .exe file is resent once and that's all (the html client does not receive the response from the server and the next connection attemps generate data transfer).
    I guess I have to change some security settings somewhere but I didn't find which.
    Does anybody have a hint ?
    Thanks.

    Hi again,
    I was finally able to solve the issue.
    I did not get any error message when using firefox, but using iExplorer provided me this error:
    "Local-with-filesystem SWF files are not permitted to use sockets"
    Googling did then allow me to find the solution here:
    http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.htm l
    The local locations on which I store my html page during the development has to be added to the trusted locations in the global security settings.
    Hope it will help some other people.
    Best regards

  • How to set proxy for client-server socket connection?

    Hi,
    I'm using the code found on the following page to create a client (mobile) to server (pc) connection and send a text message.
    http://javafaq.nu/java-example-code-503.html
    This works with mobile operators without proxy, but does nothing when the operator uses a proxy. The question is, exactly how to set the proxy and port values for using that code.
    Any help is greatly appreciated, thanks,

    It's part of the cellular settings, and is usually set up by your 3G provider. You can't choose your own proxy server

  • Multiple clients to be connected to One BI system

    Hello Experts,
      have to work on a tricky requirement.
      We have already connected one client (say R/3-100) to BI system.We are already running the deltas for the Logistics applications in BI production for this source system clent (100).
    Now the requirement is that we need to connect 4 more clients (say R/3-200,300,400,500) to the existing BI system.We need to take care of the existing delta and INIT for the LO-application for client100.
    My Doubts are :
    1) As datasources are client independent so do we need to activate the datasources (like 2lis*) in all clients one by one? or just activating in one client will make it ?
    2) If we replicate the datasources for new clients in BW side and then want to reload the data from New clients (set-up tables filling and INIT)?would it have an affect on existing deltas (for datasources 2lis*)for existing Source client 100? What shud be the precautions? How we can proceed?Please let us know your opinons plz..
    thank you,
    Balji

    1) As datasources are client independent so do we need to activate the datasources (like 2lis*) in all clients one by one? or just activating in one client will make it ?
    You need to activate the datasources individually for all the client. If you will activate in one client, it will be specific to that only
    ) If we replicate the datasources for new clients in BW side and then want to reload the data from New clients (set-up tables filling and INIT)?would it have an affect on existing deltas (for datasources 2lis*)for existing Source client 100? What shud be the precautions? How we can proceed?Please let us know your opinons plz
    If you will replicate in one client system, it wont affect delta and init from other client.
    One thing you can do, to identify data from different source systems, you can use source system compounding in your infoobjects. Make sure you are not loading data from both the client at the same time. it may lock the DSO and master data.

  • Multiple Clients in Client/Server Program

    I'm currently trying to make a small Client/Server application that will mimic a very basic chat room program. The basic idea is that the Server side of the program is started and multiple Client programs can connect and communicate with each other. However, I'm having a few problems at the moment, mostly with figuring out how it can work.
    Firstly, I can communicate one to one with the server and the client as the client socket is stored in a variable. However, to make it possible to allow multiple connections I've used a thread for each new connection but I'm not sure how I can broadcast messages to every connection. Would it be safe enough to store each client socket in a list and then communicate that way? Not sure what will happen when the client disconnects though it seems to be an issue.
    I'm also not sure how every message can be broadcasted to every single connections to the server. The server program can send a message to every client but the clients message at the moment only goes to the server. Anyway here's a bit of my code so far:
    SwingWorker<Socket, Void> worker = new SwingWorker<Socket, Void>() {
            protected Socket doInBackground() throws Exception {
                // Client socket
                try {
                    while (!stopRequested) {
                        clientSocket = serverSocket.accept();
                        // Stop requested is checked twice because the accept() method
                        // waits for a connection
                        if (!stopRequested) {
                            HostFrame.getFeedbackTextArea().append("New Connection Found");
                            Thread clientThread = new HandlerThread(clientSocket);
                            clientThread.start();
                        else {
                            serverSocket.close();
                            clientSocket.close();
                catch (Exception e) {
                    HostFrame.getFeedbackTextArea().append("Failed to Connect with Client");
                    System.out.println(e.getMessage());
                return clientSocket;
        };The SwingWorker is used so that the GUI doesn't freeze when the server tries to find a connection. At the moment it just creates a thread for each new connection but I'm guessing this isn't what I'm going to be needing to handle more than one client. Also at the moment I have no way of directing a message to a specific socket I'm pretty much just using the standard method shown on the Sun website about Sockets. Any help would be much appreciated

    clientSocket = serverSocket.accept();'clientSocket' should be a local variable here.
    else {
    serverSocket.close();
    clientSocket.close();You shouldn't close 'clientSocket here'. All you're accomplishing is closing the most recently accepted client socket. What about the others? Generally speaking you should let the client-handling threads take care of their own sockets completely.
    return clientSocket;This return statement is meaningless. You may as well return null. SwingWorker doesn't care. Don't just return something because you've got it lying around. In this case you shouldn't have it lying around.
    At the moment it just creates a thread for each new connection but I'm guessing this isn't what I'm going to be needing to handle more than one client.That is exactly what you have to do to handle more than one client. Once you fix it as per above.
    Also at the moment I have no way of directing a message to a specific socket I'm pretty much just using the standard method shown on the Sun website about Sockets.You probably need to keep a Map of client sockets accepted, keyed by some client identifier.

  • How can I connect multiple clients to a single client ?

    I am currently developing an instant messaging program.I created a server and connected multiple clients to it by using thread logic.However I do not know how to connect multiple client to a single client.
    What shall I do for that?Does anybody know a good tutorial or sample program?Or shall anybody explain me what I shall do for building the Instant Messaging part of my chat program?
    Thank u in advance.

    You may use UDP multicast socket. But since you are using the UDP protocol you might risk losing the data that you send since UDP does not guarantee the safe transfer of data.
    Alternately, you might create a server that allows multiple client to connect to it whose connection Socket objects are then stored in a Vector <Socket> object. The server then sends back data to the connected client about the other clients connected to it. Now when the client wants to send data (like an IM) to another connected client, it has to send a request to the server specifying the client login name and the server in turn streams that particular client's Address and Port to the requesting client. The requesting client then initiates the connection with the other client and then starts a conversation. One more thing, when the client communicates it needs to send information to the server like the name by which it likes to be referenced. In this scenario the server acts like a central repository for clients to query the existence of other clients in the chat room. Each client here runs a thread that listens to incoming connections and when a connection is established, may be opens a IM window or something.
    The third option is to make the server to relay the information from one client to another. Like say, I'm connected to whoopy server and i want to send "Hello" to jackson, then i send the message (ie, Hello) along with the name of the client to which i wish to send it to (ie, jackson). The server then performs a lookup in its Vector <Socket> object and then initiates a connection with jackson and sends the information. However, this method is pretty costly in that you will be wasting a lot of processing behind the server.
    --Subhankar
    P.s. If you stumble upon any other brilliant ideas let me know.

  • How to retain socket connection for multiple requests in java 1.3

    Hi All,
    My problem is to retain client socket connection without opening and closing socket connection for every request.I want to open the socket connection once and send multiple requests one after the other based upon the response over the same socket.Finally I want to close the socket only after completing all my requests and receiving respective responses.I don't want to open and close the socket for each request and response.While at the same time I expect the socket to send each request only after receiving the response for the previous request.
    I am using java 1.3 and I am looking for the solution in same version.
    Please help me .
    Thanx in advance.

    Look at my response to "Telnet to Unix box from Java"
    http://forum.java.sun.com/thread.jsp?forum=31&thread=437231
    on "Java Programming" forum. It does exactly that to run the signon and a command. It would be easy to extend it to do multiple commands.

  • Multiple input stream in one socket connection

    Can we have multiple input streams for a java socket connection? It means that in a client/server application (creates using java socket), can we have multiple input streams for the client side program. For example, the input streams are to cater for the need of letting the user to chat and downloading some files from the chat partner at the same time. And do we need to use thread to create the multiple input streams like the case when we create a multithreaded server? Anyone out there who knows the solution please post it. Thanks in advance.

    Can we have multiple input streams for a java socket
    connection? It means that in a client/server
    application (creates using java socket), can we have
    multiple input streams for the client side program.
    For example, the input streams are to cater for the
    need of letting the user to chat and downloading some
    files from the chat partner at the same time. And do
    we need to use thread to create the multiple input
    streams like the case when we create a multithreaded
    server? Anyone out there who knows the solution please
    post it. Thanks in advance.Ok im no expert here but this is what i learned:
    a Socket can have only one InputStream (Socket.getInputStream()) and one OutputStream Socket.getOutputStream()). So you will have to create a way to make multiple Socket connections in your client program. And yes, you have to use threads for your server. if you dont the client will have to wait until the user before them is finished with the connection before being able to connect. I hope this helps you out. BTW please check out http://www.javabible.com. they have the book online now for free.
    Joeyford1

  • Multiple sockets connected to one port

    Hello I am running a LabVIEW VI that is based on the Labview TCPServer example. I am wondering what the best way to deal with multiple connections to a single port would be. For example I have a device(could be thought of as the same thing as the TCPClient vi) that connects to the server using the port number and the IP address. The communication works fine when there is only one device trying to connect to the server, the problem occurs when two devices try to connect to the server. When the first device connects all data sent shows up fine, when the second device connects, the status on the device indicates a proper connection but none of the data sent shows up on the server side. I assume that I must do something with the connection ID to distinguish between the two connections, but I was wondering if there was an example or something that deals with this issue, or if someone would like to explain how I could get the data to show up properly. Any help is appreciated, thanks!

    I am hoping that there is something similar to the java api where there is some way I can start a new threads to handle multiple connections on the same port. I would assume that if java has it LabVIEW would have something similar. Unfortunately I am not sure how to go about finding out how to do such a thing in LabVIEW.
    The way that I assume the TCPListen.vi works is that there is some mechanism polling the specified port and ip address waiting for a request for a connection. Once a request is received the VI creates a connection ID so that the other subvi's can perform operations on the specific connection. It also looks as though the TCPListen.vi continues to listen for new connections, because the clients indicate a connection when more then one of them are run trying to connect to the same port and IP.
    So my question is either, how to start a parallel process to handle the new connections, or where can I find the new connection ID (because the indicator only shows the connection id of the first client to connect). Basically I am having trouble distinguishing between the multiple connections on the same port.I would like to keep all of the clients sending data through the same port if possible.Each client identifies itself in its data message so keeping the data organized is not a problem. 
    I also looked at the data socket examples, mainly because the Java examples I was looking at used "Sockets". I ran into similar troubles finding a way to create distinguishable connections using DS's as well. Anyways, any help is appreciated. Thanks.

  • File transfer to multiple clients from server socket

    I have multiple clients connected to my server socket and I need to copy more than 200mb documents from server to all clients over socket. Can we design the issue considering scalability and performance factor? What I am thinking of we should use thread for transferring file from server to client. But at the same time if we have large number of clients then we can't initialize a thread for each client. I think in this case we should initialize less than 10 threads in the pool as the file size is very large. If we keep number of threads in the pool low then probably we have to read multiple times the large server file (once for each group) which might again be a performance bottleneck. Please pour in your suggestions.

    File would be same for an instance only. For example say I have a "SEND File" button & �File Path� text box. In File Path suppose user enters the absolute path of the file and then clicks on Send File button. The responsibility of Send File button would be sending the file mentioned in the "File Path" text box to all connected client. But next time user can choose a different file.

  • Multiple socket connections with MIDP

    dear experts,
    I have a simple problem and I hope someone can help me to solve it.
    I need to open a socket connection from multiple MIDlets on the same port.
    This error occours when I try to make a socket push registration from the second (or third, or fourth...) midlet (I'm able to connect to the socket correctly from the first midlet that makes a push registration):
    PushProcessor.run Exceptionjava.io.IOException: ServerSocket Open
    java.io.IOException: ServerSocket Open
         at com.sun.midp.io.j2me.serversocket.Socket.open(+39)
         at com.sun.midp.io.j2me.socket.Protocol.openPrim(+127)
         at javax.microedition.io.Connector.openPrim(+121)
         at javax.microedition.io.Connector.open(+15)
         at javax.microedition.io.Connector.open(+6)
         at javax.microedition.io.Connector.open(+5)
         at it.myprj.midp.BasicPushMIDlet$PushProcessor.run(+16)
    I would know if push registry API allows to have multiple connection on the same socket port.
    any help is appreciated!
    giovanni

    in my opinion,
    due to the fact when an app binds one port and a second app tries to bind the same (@same time) there will ever be a exception (from my point of view)!
    an no i think that push registry cant register two apps on same port (eg datagram://5060)
    hope this helps
    chris

  • Connect CRM multiple clients to ECC

    Hi SAP Gurus,
    I have one Question regarding CRM->ECC connectivity.
    Will it be possible to connect multiple clients of CRM to ECC ? Like more than one client can talk to ECC ?
    Because in BW we can not connect multiple clients to source system ! does this true with CRM also or not ?
    Thank you

    1) As datasources are client independent so do we need to activate the datasources (like 2lis*) in all clients one by one? or just activating in one client will make it ?
    You need to activate the datasources individually for all the client. If you will activate in one client, it will be specific to that only
    ) If we replicate the datasources for new clients in BW side and then want to reload the data from New clients (set-up tables filling and INIT)?would it have an affect on existing deltas (for datasources 2lis*)for existing Source client 100? What shud be the precautions? How we can proceed?Please let us know your opinons plz
    If you will replicate in one client system, it wont affect delta and init from other client.
    One thing you can do, to identify data from different source systems, you can use source system compounding in your infoobjects. Make sure you are not loading data from both the client at the same time. it may lock the DSO and master data.

  • Connecting to multiple clients

    I have a question. i have one client and one server. the server connects a client and send some data which i am able to achieve it. my question is (is there a way to connect the same server to multiple clients?) secondly i want to make a check lets say that one client machine can accept only 30 data like (Dell $30.00). once the client recieve 30 data my client should say that i am full and then the client should write the data to another client machine ? is it possible?

    If you feel like getting fancy, a scalable server could use NIO: http://java.sun.com/j2se/1.5.0/docs/guide/nio/index.html

  • Connect Exception when I run multiple client processes

    hi All,
    I run a web logic RMI server on my machine and bind an object. When i try
    to run about 40 multiple clients (each client is a java process) i am refused
    connection. Why???

    wrong url, apparently.
    open the admin console and see that the url from your deployment is. try entering that into the browser instead of what you used to get the 404.
    also, check the logs.
    %

  • Accepting connection from multiple client

    Hi, i try to open a port on the server and allows others client to connect to this port and sent in data. It works well when it's 1 server to 1 client relationship. But when i turn on 1 server to many client connection where all the client will connect at the same time... none of the client data were capture in the server. Here is my code :
    Server code:
    static class Listener extends Thread
              public void run()
                   ServerSocket svrSocket;
                   Socket soc;
                   try
                        svrSocket = new ServerSocket(20);
                        System.out.println("---------------------------------------");
                        soc = svrSocket.accept();
                        System.out.println("---------------------------------------");
                        BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
                        String strTest;
                        while((strTest = in.readLine()) != null)
                             System.out.println("SEE THIS !!!!!!!!!!!!! " + strTest);
                   catch(Exception e)
                        e.printStackTrace();
    Client code:
    socClient = new Socket("10.1.8.101", 4444);
    outPrintWriter = new PrintWriter(socClient.getOutputStream(), true);
    outPrintWriter.println(strWrite);
    Can anyone help me??? IT"S URGENT....
    THANKS

    Your code will only handle one connection at a time currently. To handle more connections it needs to be reorganized, see below. Also, you may be having a problem with binding port 20 in your server and trying to connect to port 4444 in your client. These ports obviously have to be the same or its never going to work at all! :-)
    Without getting into thread pools and stuff, this is a sample of how you might want to organize your server.
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class SocServ implements Runnable {
        // running flag set to false to stop server.
        public static boolean isRunning=true;
        // set of servicing threads, if needed.
        private static Set servicers = new HashSet();
        public void run() {
            ServerSocket svrSocket;
            Socket soc;
            Thread t;
            // open the server socket, error if port is in use, etc.
         try {
                svrSocket = new ServerSocket(4096);
                // accept connections, and start new SocServicer threads.
                while (SocServ.isRunning) {
                    soc = svrSocket.accept();
                    t = new Thread(new SocServicer(soc));
              SocServ.servicers.add(t);
                    t.start();
                // server finished, close socket
                svrSocket.close();
            } catch (IOException e) { e.printStackTrace(); }
    import java.net.*;
    public class SocServicer implements Runnable {
         // socket connection being serviced...
         Socket s;
         public SocServicer(Socket soc) { s=soc; }
         public void run() {
              if (s==null) { return; } // for sanity
              * Do all the interaction with each socket here.
    }The idea is to run one thread that listens for connections and then spawn new threads to process each connection. This way one connection does not have to wait for the previous one to finish. For a serious application you will probably want to do some more careful management of the SocServicer threads [because each thread eats up memory & resources].

Maybe you are looking for