Port & socket

Hello ,Friend's
plz tell me wht is the definition & working of socket & port
thanks & regards

Google ( [plz tell me wht is the definition & working of socket & port|http://www.google.com/search?q=plz+tell+me+wht+is+the+definition+%26+working+of+socket+%26+port] ).

Similar Messages

  • Help with ports/sockets

    I am writing a program that accepts multiple users using sockets. It works well on my home network when i use the ip address 192.168.1.12. But when I try to get computers to connect outside of the network it doesnt work. Even when I change the ip address that the client is connecting to to the one i found at http://www.whatismyipaddress.com/
    which is 24.50.xxx.yy
    The port i'm using for the server and client is 11114.
    How do i make it work over the internet and not just my home network?

    A good place to start is:
    http://java.sun.com/j2se/1.4.1/docs/guide/rmi/socketfactory/SSLInfo.html
    There is a code example, but you will also need to follow the guide in the other link below to create the required key files.
    Don't base your knowledge of SSL RMI sockets solely on what I say here, as I'm fairly new to this so I may express myself wrong. But here is a 30,000 foot overview of what I did to get them to work:
    If you are using RSA on your SSL connection, a public and private key are required. For this to work, you must create a key (keystore) via Java's "keytool.exe" tool using the '-genkey' option (the keystore should eventually reside on your server). You will then create a certificate from that keystore using the '-export' option of the keytool. Lastly, you will import the certificate into your client's store of accepted certificates (the file java\lib\security\cacerts) via the '-import' option of keytool.
    For a full description, you need to read:
    http://java.sun.com/j2se/1.4/docs/guide/security/jsse/JSSERefGuide.html
    the section from this page on using keytool:
    http://java.sun.com/j2se/1.4/docs/guide/security/jsse/JSSERefGuide.html#CreateKeystore
    The example shows using a new custom file for the truststore, but I imported the certificate into Java's cacerts file instead. I was unable to find the certificate if it was not in this file, but I very well may have been doing something wrong.

  • Cannot close Serial port socket on Server 2008, Can on XP

    As per the subject - running the same code using the same hardware, but different OS (Server 2008 Std. NOT XP Pro)will not work!
    It's all very odd... The port opens fine but will not close using SerialPort.close(), thereby causing problems the next time the port is opened (PortInUseException).
    Has anyone here experienced this before? Any suggestions as to where the problem may lie?
    Edited by: wizzkidd on Jan 19, 2010 7:46 AM - More descriptive title

    I have a serial port monitor open on both machines; it shows that the connection is still open (on Server 2008), even after the following is run:
         public void closePort() {
              if (serialPort != null) {
                   serialPort.close();
                   Console.print("Closed port: "       + "(" + commPort + ")");
              else {
                   Console.print("Port is still open: " + "(" + commPort + ")");
         }However, on XP, the connection is closed properly.
    Upon failure to close the port, the code has already been run, however, no exception is thrown.
    Edited by: wizzkidd on Jan 19, 2010 7:56 AM

  • Port reusing problem with sockets.

    I have the following simple client/server classes. I can't get the client to reuse ports. When creating 5 sockets (not simultaneous) to the same endpoint 5 new local ports are opened and when closed set to TIME_WAIT.
    The code:
    Client:
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    public class SocketClient {
       public static void main(String[] args) {
          new SocketClient();
       public SocketClient() {
          for (int i = 0; i < 5; i++) { 
             Socket socket = new Socket();      
             try {
                socket.connect(new InetSocketAddress("tonic", SocketConstants.port));
                socket.setReuseAddress(true);
                socket.getOutputStream().write(3);
                try {
                   Thread.sleep(100);
                } catch (Exception ex) {}
                System.out.println("socket.getInputStream().read() = " + socket.getInputStream().read());
             } catch (IOException ex) {
                ex.printStackTrace();
             } finally {
                try {
                   socket.close();
                } catch (IOException ex1) {
                   //.. do nothing
    }Server:
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class SocketServer {
       public static void main(String[] args) {
          new SocketServer();
       public SocketServer() {
          ServerSocket servSocket = null;
          try {
             servSocket = new ServerSocket(SocketConstants.port);
             servSocket.setReuseAddress(true);
          } catch (IOException ex) {
             ex.printStackTrace();
          while (true) {
             Socket socket = null;
             try {
                socket = servSocket.accept();
                System.out.println("socket.getRemoteSocketAddress() = " + socket.getRemoteSocketAddress());
                System.out.println("socket.getInputStream().read() = " + socket.getInputStream().read());
                socket.getOutputStream().write(4);
                System.out.println("socket.getInputStream().read() = " + socket.getInputStream().read());
                try {
                   Thread.sleep(400);
                } catch (Exception ex) {
                   ex.printStackTrace();
             } catch (Exception ex) {
                ex.printStackTrace();
             } finally {
                if (socket != null) {
                   try {
                      socket.close();
                   } catch (IOException ex) {
                      ex.printStackTrace();
    }Do I need to use socket.bind(..) or how can I get my client to reuse ports in TIME_WAIT state?

    The TIME_WAIT state is there for a reason; it's your friend and it's there to help you :-)
    - The Socket FAQ: http://www.developerweb.net/forum/showthread.php?t=2941
    Why do you think TIME_WAIT is a problem? Try not to shoot yourself in the foot; don't use setReuseAddress(true). Read the FAQ entry.

  • How do I monitor two service ports in a server ?

    The web service is alive when tcp port 80 and 8080 are both alive. How do I use script to monitor both ports at the same time ? Any example for this case ? Thanks.

    Here is a script I have written for this - you can test as many ports as you want on one server with this script.
    To run just add under the service as:
    service test
    keepalive type script socket-test.txt "172.17.10.10 8080 80 443"
    Hope this helps,
    Regards,
    Darren.
    -------------- Begin Script -----------------------------
    !======================================================
    ! Filename: socket-test.txt
    ! Parameters: Host port1 port2 port3
    ! This script does the following:
    ! Connects to a remote host on a specified tcp sockets,
    ! waits for X seconds and then disconnects.
    ! Failure Upon:
    ! Not establishing a connection with the host. If one connection
    ! fails, the script fails.
    ! Usage to run manually:
    ! script play socket-test.txt
    ! Useage to run automaticlly:
    ! cmd-sched
    ! cmd-sched record 1 * * * * * "script play socket-test.txt"
    ! Written by Darren Page, Dimension Data
    !======================================================
    !no echo
    ! Make sure the user has a qualified number of arguments
    if ${ARGS}[#] "LT" "2"
    echo "Usage: socket-test.txt \'host socket1 socket2 socket3 ...'"
    exit script 1
    endbranch
    set host "${ARGS}[1]"
    ! get the first tcp port ready from the ARGS array
    var-shift ARGS
    while ${ARGS}[#] "GT" "0"
    set EXIT_MSG "Connect: Failed to connect to ${host}"
    ! Connect to remote host on specified port
    socket connect host ${host} port ${ARGS}[1] tcp 2000
    ! Wait one second
    pause 1
    ! disconnect from remote host with a TCP FIN
    socket disconnect ${SOCKET} graceful
    ! Wait one second
    pause 1
    !get the next port from the array
    var-shift ARGS
    no set EXIT_MSG
    ! Demarcation of the end of the loop
    endbranch
    exit script 0
    -------------End of Script ------------------

  • HT2792 Just purchased from an airport store the MagSafe Airline Adapter so I could use my MacBook Air on a long haul flight. But, the airline adapter plug doesn't fit the socket. Am I missing something?

    I purchased at the airport last week before a long haul flight the MagSafe Airline Adappter so I couod keep working on the MacBook Air without fear of the battery running out before I had completed the necessary work. The shop assistant assured me the kit worked on all planes but......the socket on the flight, both outbound and inbound, was the normal female 2 pin/3 pin socket that I used to use for my old thinkPad. What am I doing wrong? Am I missing something obvious here
    Thanks for any help you can offer.
    Geoff

    Hi CaptFred,
    Thanks for taking the time to respond. I understand your point and have indeed separated them. Since sending the message I have visited the Apple Store to check the picture of the accessory in case I was missing something and I wonder if I am missing the 20mm adapter but, over and above that, I just dont see the right size/shape empower port socket in the plane seat, only the traditional 3 pin/2 pin sockets. I wonder if the salesman was selling me a pig in the poke because the Apple Store also says that it fits some commercial airlines whereas the salesman told me it worked in all flights. I suspect I will need to go to the airline companies direct to see which planes have this particualr Empower port. In the meantime I am tempted to ask for my money back. Geoff

  • Socket connection timeout

    I have a simple threaded client application to connecting to the server
    which is also threaded. I am using the following code to prevent(reduce)
    connection timeouts, but it doesn't seem like timeout period elapses
    before exception is thrown on the client side. Any ideas? Exception
    occurs way before 10 seconds as specified in the code below.
    InetAddress addr = InetAddress.getByName(this.serverName);          
    SocketAddress sockaddr = new InetSocketAddress(addr,this.port);
    Socket socket = new Socket();
    socket.connect(sockaddr,10000);
    The exception I get on the client side is:
    java.net.ConnectException: Connection refused: connect
    Thanks

    The timeout kicks in if the other end hasn't responded within the period. In this case the other end has refused the connect attempt, probably because nothing is listening on the requested port. This can happen well within the timeout period, as you have experienced.

  • Socket seems too slow...maybe java.nio?

    Hello
    In our system I have to receive Multicast Packets repeats very quick(1-5 ms). I have to link them one after an other in the order they sent. And if I miss a packet, something will go wrong...
    I have to listen to different IPs and I use different threads for different IPs. If I use only one thread (and listens to only one IP) everything seems ok.
    But if I starts listening to an other ip too, I miss 2 packets in a row, or only one if I turn off parsing the message (XML).
    Here is the code I use in the Threads:
    try{
                   socket = new MulticastSocket(port);
                   socket.setSoTimeout(1000);
                   inetAddress = InetAddress.getByName(ip);
                   NetworkInterface nInterface=
    NetworkInterface.getByName(networkInterface);
                   if(nInterface!=null)socket.setNetworkInterface(nInterface);
                   socket.joinGroup(inetAddress);
              catch(IOException ioe){
                   logger.error(ioe.getMessage(), ioe);
    return;
              try{
                   while (!interrupted()) {
                        try{
                             byte[] buffer = new byte[1480];
                             packet = new DatagramPacket(buffer, buffer.length);
                             socket.receive(packet);
    parse(buffer);
                        }catch(SocketTimeoutException stoe){
                             //     DO NOTHING
                        }catch(IOException ioe){
                             logger.error(ioe.getMessage(), ioe);
              }finally{
                   try {
                        if(socket!=null){
                             socket.leaveGroup(inetAddress);
                   } catch (IOException ioe) {}
    Every Thread has its own parsing object.
    Any tips, what is wrong?
    Maybe java.nio could solve the problem somehow. There is a sample server in [Java Home]/sample/nio/server and it suggest that there are quicker methods to receive messages from different IPs (maybe Blocking/Pooled-Thread Server). But I can't understand the API and the Sample while I was reading it (20-30 minutes).
    Could it be quicker? Does it worth toying with the idea?
    Thanks:
    Bence

    In our system I have to receive Multicast Packets
    repeats very quick(1-5 ms). I have to link them one
    after an other in the order they sent. And if I miss
    a packet, something will go wrong...There is no guarantee anywhere in the system that you won't miss a datagram. UDP doesn't make such guarantees. If you need all the packets you will have to build ACK or NACK into your protocol.
    You can alleviate the problem by running a very large socket receive buffer. But you can't eliminate it. Rethink this.
    NIO is not significantly quicker for applications like this, it is more scalable.

  • Is it possible for two servers to receive broadcasts on the same port?

    I'm trying to run multiple instances of a class that creates a UDP socket that receives broadcast packets on a specific port:
    socket = new DatagramSocket(port);
    The second and succeeding instances get a BindException because the address is already in use. Is there a way to have multiple servers on a specific port?

    It works. So now instead of just new DatagramSocket(port), my code now reads:
    socket = new DatagramSocket(null);
    socket.setReuseAddress(true);
    SocketAddress sockAddr = new InetSocketAddress(port);
    socket.bind(sockAddr);
    Thanks.

  • "Error establishing socket" error on JDBC Receiver Channel.

    Dear All,
    Scenario: Soap to JDBC.
    I m getting error on JDBC Receiver Channel. messages are processed succesfully on ABAP Stack and receiver channel is on below error:
    ERROR : Message processing failed. Cause: com.sap.aii.af.ra.ms.api.RecoverableException: Error when attempting to get processing resources: com.sap.aii.af.service.util.concurrent.ResourcePoolException: Unable to create new pooled resource: DriverManagerException: Cannot establish connection to URL 'jdbc:microsoft:sqlserver://156.5.202.194:3312;DatabaseName=ODW': SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Error establishing socket.
    Note: i already tested another interface with this same IP and it was fine with different port.
    jdbc:microsoft:sqlserver://IP:PORT;DatabaseName=Name
    Regards,
    Manikandan

    and it was fine with different port
    socket exception is (always) related to port....did you check with the network team about this new Port?

  • Data Sockets Problem

    Hi,
    I have written an applet with the following code that opens a simple socket. The problem is that I can only run one copy of the applet at once or I get an IOException can not create socket. Can any help me out
    Thanks for any help
    Joolz
    //// Start Code ////
    public tcpip(InetAddress ipa, int port)
    Socket _given = null;
    try
    _given = new Socket(ipa.getHostAddress(),port);
    catch(IOException e) {System.out.println("Error creating socket..");
        return;
    //// End Code ////

    Hi,
    Here is the error message, I don't have access to the server.
    Error creating socket java.net.connectException Connection refused connect.
    Thanks
    Joolz

  • Applet socket problem in client-server, urgent!

    Dear All:
    I have implemented a client server teamwork environment. I have managered to get the server running fine. The server is responsible for passing messages between clients and accessing Oracle database using JDBC. The client is a Java Applet. The code is like the following. The problem is when I try to register the client, the socket connection get java.security.AccessControlException: access denied(java.net.SocketPermission mugca.its.monash.edu.
    au resolve)
    However, I have written a Java application with the same socket connection method to connect to the same server, it connects to the server without any problem. Is it because of the applet security problem? How should I solve it? Very appreciate for any ideas.
    public class User extends java.applet.Applet implements ActionListener, ItemListener
    public void init()
    Authentication auth = new Authentication((Frame)anchorpoint);
    if(auth.getConnectionStreams() != null) {
    ConnectionStreams server_conn = auth.getConnectionStreams();
    // Authenticates the user and establishes a connection to the server
    class Authentication extends Dialog implements ActionListener, KeyListener {
    // Object holding information relevant to the server connection
    ConnectionStreams server_conn;
    final static int port = 6012;
    // Authenticates the user and establishes connection to the server
    public Authentication(Frame parent) {
    // call the class Dialog's constructor
    super(parent, "User Authentication", true);
    setLocation(parent.getSize().width/3, parent.getSize().height/2);
    setupDialog();
    // sets up the components of the dialog box
    private void setupDialog() {
    // create and set the layout manager
    //Create a username text field here
    //Create a password text field here
    //Create a OK button here
    public void actionPerformed(ActionEvent e) {
    authenticateUser();
    dispose();
    // returns the ConnectionStreams object
    public ConnectionStreams getConnectionStreams() {
    return(server_conn);
    // authenticates the user
    private void authenticateUser() {
    Socket socket;
    InetAddress address;
    try {
    // open socket to server
    System.out.println("Ready to connect to server on: " + port);
    socket = new Socket("mugca.its.monash.edu.au", port);
    address = socket.getInetAddress();
    System.out.println("The hostname,address,hostaddress,localhost is:" + address.getHostName() + ";\n" +
    address.getAddress() + ";\n" +
    address.getHostAddress() + ";\n" +
    address.getLocalHost());
    catch(Exception e) {
    displayMessage("Error occured. See console");
    System.err.println(e);
                                  e.printStackTrace();
    }

    Hi, there:
    Thanks for the help. But I don't have to configure the security policy. Instead, inspired by a message in this forum, I simply upload the applet to the HTTP server (mugca.its.monash.edu.au) where my won server is running. Then the applet is download from the server and running fine in my local machine.
    Dengsheng

  • Send Object through Socket

    Hi,
    I am trying to send an object from Server to Client but the ObjectInputStream.readObject() on the client blocks.
    net beans Project can be found Here .
    Why it doesn't work?
    Thanks,
    Itay

    The Server works fine... it waits for a second client after the first one get connected
    I will post here the code.
    Server Code
    public class MemoryServer
        private final static int DEFAULT_BOARD_SIZE = 4;
        private ServerSocket socket;
         * Starting the server
         * @param n integer to determine the size of the board (must be even) the board will be n*n.
         * @param port the port on which the server will listen for incoming requests
        public void startServer(int n, int port)
            try
                socket = new ServerSocket(port);
            catch (IOException e)
                e.printStackTrace();
                System.exit(1);
            while(true)
                System.out.println("Listening on port " + port);
                Socket firstPlayerSocket = null, secondPlayerSocket = null;
                try
                    firstPlayerSocket = socket.accept();
                    System.out.println("First Player Socket Open: " + firstPlayerSocket.getInetAddress() + ":" + firstPlayerSocket.getPort());
                    MemoryGame game = new MemoryGame(n, firstPlayerSocket);
                    secondPlayerSocket = socket.accept();
                    System.out.println("Second Player Socket Open: " + secondPlayerSocket.getInetAddress() + ":" + secondPlayerSocket.getPort());
                    game.setSecondPlayer(secondPlayerSocket);
                    game.start();
                catch (IOException e1)
                    try
                        e1.printStackTrace();
                        if (firstPlayerSocket != null)
                            firstPlayerSocket.close();
                        if (secondPlayerSocket != null)
                            secondPlayerSocket.close();
                    catch (IOException e2)
                        e2.printStackTrace();
    public class MemoryGame extends Thread
        private Socket firstPlayerSocket, secondPlayerSocket;
        private ObjectOutputStream firstPlayerOut, secondPlayerOut;
        private ObjectInputStream firstPlayerIn, secondPlayerIn;
        private int boardSize;
        public MemoryGame(int boardSize, Socket firstPlayer) throws IOException
            this.boardSize = boardSize;
            firstPlayerSocket = firstPlayer;
            firstPlayerOut = new ObjectOutputStream(firstPlayerSocket.getOutputStream());
            firstPlayerOut.flush();
            firstPlayerIn = new ObjectInputStream(firstPlayerSocket.getInputStream());
            TextMessage message = new TextMessage("Waiting for opponent.");  //TextMesaage extends Message which implements Serializable
            firstPlayerOut.writeObject(message);
            firstPlayerOut.flush();
        public void setSecondPlayer(Socket secondPlayer) throws IOException
            try
                secondPlayerSocket = secondPlayer;
                secondPlayerOut = new ObjectOutputStream(secondPlayerSocket.getOutputStream());
                secondPlayerOut.flush();
                secondPlayerIn = new ObjectInputStream(secondPlayerSocket.getInputStream());
                TextMessage message = new TextMessage(Constants.GAME_START_MESSAGE);
                firstPlayerOut.writeObject(message);
                firstPlayerOut.writeObject(message);
            catch(IOException e)
                firstPlayerIn.close();
                firstPlayerOut.close();
                if (secondPlayerIn != null)
                    secondPlayerIn.close();
                if (secondPlayerOut != null)
                    secondPlayerOut.close();
                throw e;
        @Override
        public void start()
            endGame();
        private void endGame()
            try
                firstPlayerIn.close();
                firstPlayerOut.close();
                firstPlayerSocket.close();
                secondPlayerIn.close();
                secondPlayerOut.close();
                secondPlayerSocket.close();
            catch (IOException e)
                e.printStackTrace();
    }Client Code
    public class MemoryClient
        private Socket socket;
        public MemoryClient(String host, int port)
            try
                socket = new Socket(host, port);
                ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
                System.out.println("Connected to " + host + ":" + port);
                while (true)
                    try
                        Message msg = (Message)in.readObject();
                        System.out.println("Recieved");
                        if (msg instanceof TextMessage)
                            TextMessage textMsg = (TextMessage)msg;
                            if (!textMsg.getText().equals(Constants.GAME_START_MESSAGE))
                                System.out.println(textMsg.getText());
                                break;
                            MemoryFrame gameFrame = new MemoryFrame(socket);
                            gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    catch(Exception e)
                        e.printStackTrace();
            catch (IOException e)
                e.printStackTrace();
                System.exit(1);
    }

  • Two sockets in a single server

    May I open two sockets with different listening port numbers in a single server? For each socket, the way to deal with the inputstream and outputstream is different. May the thread be like this:
    public class twoSocketServer implements Runnable {
    public twoSocketServer() {
    try{
    SSLServerSocketFactory fact = SSLServerSocketFactory.getInstance(rand, selfPrivateKey, selfCertificate, trustEngine, null);
    serverSocket1 = (SSLServerSocket) fact.createServerSocket(ListeningPort1);
    serverSocket1.setNeedClientAuth(false);
    serverSocket2 = (SSLServerSocket) fact.createServerSocket(ListeningPort2);
    serverSocket2.setNeedClientAuth(false);
    } catch {...}
    public void run()
    while(true)
    try
    SSLSocket socket1 = (SSLSocket) serverSocket1.accept();
    new handler1(socket1).start();
    SSLSocket socket2 = (SSLSocket) serverSocket2.accept();
    new handler2(socket2).start();
    } catch {...}
    class handler1 extends Thread {...}
    class handler2 extends Thread {...}
    Is there something wrong with this idea? If yes, how can I correct it? Thanks.

    This is better :
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    public class MultSrv extends JFrame
         JTextArea   panel   = new JTextArea();
         JScrollPane sbr     = new JScrollPane(panel);
         Vector      sockets = new Vector();
         Vector      servers = new Vector();
    public MultSrv() 
         super();
         SocServer ss1 = new SocServer(this,4444);
         if (ss1.servS != null) ss1.start();
              else               System.out.println("err");
         SocServer ss2 = new SocServer(this,4445);
         if (ss2.servS != null) ss2.start();
              else               System.out.println("err");
         SocServer ss3 = new SocServer(this,4446);
         if (ss3.servS != null) ss3.start();
              else               System.out.println("err");
         try
              InetAddress inet = InetAddress.getLocalHost();
              setTitle("MultServer v1 - "+inet+"  Port=4444/5/6");
         catch(IOException e){}
         setBounds(10,10,400,450);
         setContentPane(sbr);
         panel.setEditable(false);
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {   dispose();
                   System.exit(0);}});
         setVisible(true);
         javax.swing.Timer ta = new javax.swing.Timer(2000, new ActionListener()
              public void actionPerformed(ActionEvent e)
                   panel.setText("");
                   for (int i = 0; i < sockets.size(); i++)
                        SocServer ss = (SocServer)sockets.get(i);
                        if (ss.servS == null) panel.append(""+ss.port +ss.err);
                             else              panel.append(""+ss.port +" Active");
                        panel.append("\n");     
                   for (int i = 0; i < servers.size(); i++)
                        Server server = (Server)servers.get(i);
                        panel.append(""+server.clnt.getInetAddress()+" Is serviced");
                   repaint();
         ta.start();     
    public void go(Socket clnt)
         Server server = new Server(clnt);
         servers.add(server);
         server.start();
    //  The ServerSocket
    public class SocServer extends Thread
         ServerSocket servS;
         int          port;
         String       err = "";
         Socket       clnt;
         MultSrv      mserv;
    public SocServer(MultSrv mserv, int port) 
         this.mserv = mserv;
         this.port  = port;
         sockets.add(this);
         try
              servS = new ServerSocket(port);
         catch (IOException e)
              err = e.toString();;
    public void run()
         try
              while (true)
                   clnt = servS.accept();
                   mserv.go(clnt);
         catch (IOException e)
    //  The Server.. one for each client
    public class Server extends Thread
         Socket                clnt = null;
         OutputStream       out  = null;
         InputStream        ins  = null;
    public Server(Socket soc) 
         clnt = soc;
    public void run()
         try
              ins  = clnt.getInputStream();
              out  = clnt.getOutputStream();
              while (true)
         catch (IOException e){}
         try
              ins.close();
              out.close();
              clnt.close();
         catch (IOException e){}
    public static void main (String[] args) 
         new MultSrv();
    }     

  • Multi-threaded performance server using 2 ports to two-way communication

    Hi, I'm new in the forums so welcome everyone. I'm developing now an online computer game based on orginal Polish board-game, but it doesn't mean. Important is that I need to develope a high-performance multi-threaded server, which can serve... let's say few hundres of games, and a thousend of players simulateously. My server works on two ports/sockets.
    First one is represented by "ServerSocketChannel clientConSsc" in my code. The main thread in my server class which invokes the method "run()" (which You can see below), registers clientConSsc with Selector and then repeatingly accepts incoming connections from clients on this socket. When connection(channel) is estabilished and clients wants to write some request to this channel, the main thread on server creates a new instance of class "RequestHandler" which extends Thread and handles this request (reads the request from channel, makes some changes on server, spreads some new messages to other clients in the same game and so on... everything on the same socket/port/channel). Then the channel/connection is closed by the server - I call such connections: "a short connections". In the same time the main thread continues the loop and is still able to accept connections from another players. That's the idea of multi-threaded server, right? :) And to this point, everything works fine, but... what if the server wants to trigger some new command, write new information to client?
    Server could have tried to open a SocketChannel to client's IP address, but then the client programme would have to create and ServerSocketChannel object, bind it to some InetAddress and then... and then client becomes a server! - that breaks the idea of client-server cooperation and demands on players of my game to have routed some port on their machines. To resolve this problem I made some sort of "system" which, when some player/client is logging into my server, accepts second (this time constant, not "short") connection on the second port I mentoined on the beginning. This connection is held in variable "SocketChannel serverCon" of class "Player" - which reflects a player logged onto server. Server maintains every such connection till the client logs off. After the connection is accepted, the player whom connection it was is added to collection called "playersToRegisterToWrite". After the Selector.selectNow() is invoked (as You can see in the code below), each and every player's connection is registered in selector (with selection key - OP_WRITE and attachment pointing on owning player). In the same time client's code is trying to read some bytes from this connection and blocks on it until some bytes are written to this connection. When server wants to "tell" something to client, deliver some message/command, it creates a new instance of class which extends an abstract class called "ServerAction" (another new thread) and adds it to collection "actionsToDo". In ServerAction's method "run()" there are whole code to interact with client (e.g. send an update of players' list, an update of games' list, a chat message). Finnaly when Selector informs the server that some connection is writable (some client is waiting for commands), then server checks if there's any "actionToDo" involving this client/player. If there is, it unregisters the connection from Selector (so no other ServerAction (thread) can write on this connection) and starts the action. At the end of every "run()" method of subclass of ServerAction there's a code, which again adds the player to collection "playersToRegisterToWrite", so the player's connection can again be registered in Selector and the player can again receive informations from server - after it consumed THIS "ServerAction".
    It looks to me like it should be working fine, but it's not. When I test my server and clients on the same machine (no ping/latency) everything seems to be working fine. But when it comes to play my game with somebody even on LAN or through the Internet there comes the problems. My first socket I describe (and first type of connections - short connections) works perfectly fine, so the requests triggered by client are delivered and handled properly. But the second socket is cirppling. For example: the server triggers a command refering to an update of clients logged to server' list. It is triggered by Selector so the client should be ready to read data from server, so the server sends data! And the client never receives it... Why?
    It experimented a whole lot of time on SocketChannel's method "configureBlocking(boolean)", but it never helps. I think the client should always block it's listening thread on connection, contratry to server which is ment to be fast, so it should send the data through non-blocking channels. Am I right? Are there any rules refering blocking configuration of SocketChannels?
    I will be grateful for every answer. To help You out I attach also drafts from run()'s methods of my classes.
    Server's main method - main thread :
        public void run() {
           try {
                selector = Selector.open();
                clientConSsc.configureBlocking(false);
                clientConSsc.register(selector , SelectionKey.OP_ACCEPT);
                while(serverRunning) {
                    try {
                        selector.selectNow();
                        Iterator it;
                        synchronized(playersToRegisterToWrite) {
                            it = playersToRegisterToWrite.iterator();
                            while(it.hasNext()) {
                                Player player = (Player)it.next();
                                it.remove();
                                player.serverCon.configureBlocking(false);
                                player.serverCon.register(selector , SelectionKey.OP_WRITE , player);
                        Set keys = selector.selectedKeys() {
                        it = keys.iterator();
                        while(it.hasNext()) {
                            SelectionKey key = (SelectionKey)it.next();
                            if(key.isAcceptable()) {
                                it.remove();
                                clientCon = clientConSsc.accept();
                                clientCon.configureBlocking(false);
                                clientCon.register(selector , SelectionKey.OP_READ);
                                continue;
                            if(key.isReadable()) {
                                it.remove();
                                key.cancel();
                                new RequestHandler(this , (SocketChannel)key.channel()).start();
                                continue;
                            if(key.isWritable()) {
                                if(key.attachment() != null ) {
                                    ServerAction action = null;
                                    synchronized(actionsToDo) {
                                        Iterator aIt = actionsToDo.iterator();
                                        while(aIt.hasNext()) {
                                            ServerAction temp = (ServerAction)aIt.next();
                                            if(temp.getPlayer().equals((Player)key.attachment())) {
                                                action = temp;
                                                aIt.remove();
                                                break;
                                    if(action != null) {
                                        key.channel().configureBlocking(false);
                                        it.remove();
                                        key.cancel();
                                        action.start();
                                continue;
                    } catch(Exception e) {
                        statusArea.append(e.toString() + "\n");
                        e.printStackTrace();
                        continue;
            } catch(ClosedChannelException e) {
                statusArea.append(e.toString() + "\n");
            } catch(IOException e) {
                statusArea.append(e.toString() + "\n");
                A part of server's RequestHandler's class' method run() - the method which handles requests triggered by client on first port:
    public void run() {
            boolean served = false;
                try {
                    channel.configureBlocking(true);
                    retryCount++;
                    retry = false;
                    String command = ns.readText(channel).trim();
                    ns.statusArea.append("ktos przesyla komende: " + command + "\n");
                    if(command != null && !command.equals("ERROR")) {
                        String[] cmd = command.split("�");
                        ns.statusArea.append("komenda: " + cmd[0] + "\n");
                        if(cmd[0].equals("CHAT")) {
                            if(cmd.length != 5) {
                                retry();
                            } else {
                                if(cmd[2].equals("NOGAME")) {      // jezeli nie ma okreslonej gry czyli rozsylamy do wszystkich
                                    for(int i = 0 ; i < ns.loggedPlayersListItems.size() ; i++) {
                                        Player current = (Player)ns.loggedPlayersListItems.get(i);
                                        if(current.state == Player.CHOOSING && !current.equals(new Player(Integer.parseInt(cmd[1]))))   // jezeli gracz jest w okienku wybierania gry to wysylamy mu broadcast
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                } else {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(new Game(Integer.parseInt(cmd[2]))));
                                    for(int i = 0 ; i < game.players.size() ; i++) {
                                        Player current = (Player)game.players.get(i);
                                        if(!current.equals(new Player(Integer.parseInt(cmd[1]))))
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                served = true;
                        } else if(cmd[0].equals("GETGAMEINFO")) {
                            if(cmd.length != 3)
                                retry();
                            else {
                                int gameID = Integer.parseInt(cmd[2]);
                                ns.statusArea.append("poproszono o informacje o grze nr: " + gameID + "\n");
                                Game checkedGame = new Game(gameID);
                                if(ns.gamesListItems.contains(checkedGame)) {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(checkedGame));
                                    channel.configureBlocking(true);
                                    ObjectOutputStream oos = new ObjectOutputStream(channel.socket().getOutputStream());
                                    oos.writeObject(game);
                                    oos.writeObject(game.players);
                                    oos.flush();
                                    ns.statusArea.append("wyslano informacje o grze nr: " + gameID + "\n");
                                } else {
                                    ns.statusArea.append("brak gry o nr: " + gameID + "\n");
                                served = true;
                } catch(IOException e) {
                    e.printStackTrace();
            if(!served) {
                ns.findAndDisconnectPlayer(channel);
            try {
                channel.close();
            } catch(IOException e) {
                e.printStackTrace();
        }An example of ServerAction's subclass - the class which triggers server commands to client on second port:
    class UpdateLoggedPlayersList extends ServerAction {
        public UpdateLoggedPlayersList(NeuroServer ns , Player player) {
            super(ns , player);
        public void run() {
            try {
                serverCon.configureBlocking(true);
                ns.sendText("UPDATELOGGEDPLAYERSLIST" , serverCon);
                if(ns.readText(serverCon).equals("OK")) {
                    ObjectOutputStream oos = new ObjectOutputStream(serverCon.socket().getOutputStream());
                    oos.writeObject(ns.loggedPlayersListItems);
                    oos.flush();
                synchronized(ns.playersToRegisterToWrite) {
                     ns.playersToRegisterToWrite.add(player);
            } catch(IOException e) {
                e.printStackTrace();
    }A part of client's CmdHandler's class' method run() - the method which handles commands triggered by server:
    public void run() {
        try {
            while(works) {
                String command = nc.readText(nc.serverCon);
                System.out.println("Server przesyla komende: " + command + "\n");
                String[] cmd = command.split("�");
                if(cmd[0] != null && !cmd[0].equals("ERROR")) {
                    if(cmd[0].equals("CHAT")) {
                        if(nc.chooseGameDialog != null && nc.chooseGameDialog.isVisible()) {     // jezeli na wybieraniu gry
                            newChatEntry(cmd[2] , null , cmd[3] , nc.chooseGameDialog.chatPane);
                        } else if(nc.readyDialog != null && nc.readyDialog.isVisible()) {  // jesli na przygotowywaniu
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.readyDialog.chatPane);
                        } else if(nc.ng != null) {                   // jesli w grze
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.ng.inGameChatPane);
                    } else if(cmd[0].equals("UPDATELOGGEDPLAYERSLIST")) {
                        nc.sendText("OK" , nc.serverCon , false);
                        nc.serverCon.configureBlocking(true);
                        ObjectInputStream ois = new ObjectInputStream(nc.serverCon.socket().getInputStream());
                        DefaultListModel players = (DefaultListModel)ois.readObject();
                        nc.chooseGameDialog.updateLoggedPlayersList(players);
        } catch(IndexOutOfBoundsException e) {
            System.out.println(e);
        } catch(IOException e) {
            System.out.println(e);
        } catch(ClassNotFoundException e) {
            System.out.println(e);
    }And two methods I used in codes above: sendText(String text , SocketChannel sc) and readText(SocketChannel sc) - they are my "utility" methods, which I use to send and receive Strings through specified SocketChannels.
    boolean sendText(String text , SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        boolean sendRetry;
        boolean sent = false;
        do {
            sendRetry = false;
            try {
                StringBuffer cmd = new StringBuffer();
                cmd.setLength(0);
                if(text.length()+4 < 100)
                    cmd.append("0");
                if(text.length()+4 < 10)
                    cmd.append("0");
                cmd.append(Integer.toString(text.length()+4) + "�");
                cmd.append(text);
                cmd.append("\n");
                bbuf = charset.encode(CharBuffer.wrap(cmd));
                sc.write(bbuf);
                bbuf.clear();
                int n = sc.read(bbuf);
                if(n == 1) {
                    bbuf.flip();
                    Byte re = bbuf.get();
                    if(re == 1) {
                        sendRetry = true;
                    } else {
                        sent = true;
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return false;
        } while(!sent && sendRetry);
        return true;
    String readText(SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        int readRetryCount = -1;
        boolean readRetry;
        do {
            readRetry = false;
            readRetryCount++;
            StringBuffer cmd = new StringBuffer();
            cmd.setLength(0);
            bbuf.clear();
            try {
                readLoop:
                while(true) {
                    int n = sc.read(bbuf);
                    if(n > 0) {
                        bbuf.flip();
                        CharBuffer cbuf = charset.decode(bbuf);
                        while(cbuf.hasRemaining()) {
                            char c = cbuf.get();
                            if(c == '\r' || c == '\n') break readLoop;
                            cmd.append(c);
                    } else break;
                statusArea.append(Thread.currentThread().getId() + " readText() odczytuje: " + cmd.toString() + "\n");
                if(cmd.length() < 3 || Integer.parseInt(cmd.substring(0 , 3)) != cmd.length()) {
                    sc.write(ByteBuffer.wrap(new byte[] {1}));
                    readRetry = true;
                } else {
                    sc.write(ByteBuffer.wrap(new byte[] {0}));    // length OK
                    return cmd.toString().substring(4 , cmd.toString().length());
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return "ERROR";
        } while(readRetry && readRetryCount < 3);
        findAndDisconnectPlayer(sc);
        try {
            sc.close();
        } catch(IOException e) {
            e.printStackTrace();
        return "ERROR";
    }Edited by: Kakalec on Jul 23, 2008 11:04 AM

    You seem to be using a horrendous mixture of PrintWriters, BufferedReaders, ObjectOutputStreams, and no doubt ObjectInputStreams. You can't do that.
    Some rules about this:
    (a) Whenever you use a stream or reader or writer on a socket, you must allocate it once for the life of the socket, not every time you want to do an I/O.
    There are many reasons for this including losing buffered data in the old stream and auto-closure of the socket on garbage-collection of the old stream.
    (b) You can't mix stream types on the same socket. (i) If you're writing objects, use an ObjectOutputStream, you must read with an ObjectInputStream, and you can't read or write anything that isn't supported by the API of ObjectOutputStream. (ii) If you're writing lines, use a BufferedWriter and a BufferedReader at the other end. If you're writing characters, use a Writer and a Reader. (iii) If you're writing primitive data or UTF strings, use a DataOutputStream and a DataInputStream. (iv) If you're writing bytes, use DataOutputStream and a DataInputStream or an OutputStream and an InputStream. You can't mix (i), (ii), (iii), and (iv).
    (c) Don't use PrintWriter or PrintStream over the network. They swallow exceptions that you need to know about. They are for writing to the console, or log files, where you don't really care about exceptions.
    (d) Call flush() before reading.
    (e) Always close the 'outermost' output stream or writer of a socket, never the input stream or the socket itself. Closing any of these closes the socket and therefore makes the other stream unusable, but only closing the output stream/writer will flush it.

Maybe you are looking for