Multithread socket programming

Hello,
I'm new to socket programming world.
I've to send/receive the data from a external system thru socket. Since # of data to be processed is huge, I'm thinking to have multiple threads to send/receive thru socket. It looks like socket is NOT thread safe. So I'm thinking to have separate socket connection for each thread. Each thread will create the new socket connection and close it before it dies. Creating a new socket for each thread does not seem to be good practice to me.
Is this good design for socket programming? If not, please share your ideas.
I'm also thinking to have socket connecting pooling to re-use the connections. Is there any lib for doing this?
Thanks for the help

sorry i was busy on something else till now. thanks for reply.
Lets say that I've 100 request xml in the blocking queue. I would like to have producer/consumer model. producer will write the request from queue to channel and consumer will capture the response from channel . so sending/receiving happens simultaneously.
If I have single channel, I''m still not quite sure how i can read/write from channel at the same time. Please clarify with some examples.
i went thru few article and found following code to read/write. here looks like i have to write all 100 request first into channel and then be ready to read response. is my understanding correct?
// Check what event is available and deal with it
if (key.isConnectable()) {
// finishConnection(key);
} else if (key.isReadable()) {
this.read(key);
} else if (key.isWritable()) {
this.write(key);
}

Similar Messages

  • Design question for database connection in multithreaded socket-server

    Dear community,
    I am programming a multithreaded socket server. The server creates a new thread for each connection.
    The threads and several objects witch are instanced by each thread have to access database-connectivity. Therefore I implemented factory class which administer database connection in a pool. At this point I have a design question.
    How should I access the connections from the threads? There are two options:
    a) Should I implement in my server class a new method like "getDatabaseConnection" which calls the factory class and returns a pooled connection to the database? In this case each object has to know the server-object and have to call this method in order to get a database connection. That could become very complex as I have to safe a instance of the server object in each object ...
    b) Should I develop a static method in my factory class so that each thread could get a database connection by calling the static method of the factory?
    Thank you very much for your answer!
    Kind regards,
    Dak
    Message was edited by:
    dakger

    So your suggestion is to use a static method from a
    central class. But those static-methods are not realy
    object oriented, are they?There's only one static method, and that's getInstance
    If I use singleton pattern, I only create one
    instance of the database pooling class in order to
    cionfigure it (driver, access data to database and so
    on). The threads use than a static method of this
    class to get database connection?They use a static method to get the pool instance, getConnection is not static.
    Kaj

  • Java Swing and Socket Programming

    I am making a Messenger like yahoo Messenger using Swing and Socket Programming ,Multithreading .
    Is this techology feasible or i should try something else.
    I want to display my messenger icon on task bar as it comes when i install and run Yahoo Messenger.
    Which class i should use.

    I don't really have an answer to what you are asking. But I am developing the same kind of application. I am using RMI for client-server and server-server (i have distributed servers) communication and TCP/IP for client-client. So may be we might be able to help each other out. My email id is [email protected]
    Are you opening a new socket for every conversation? I was wondering how to multithread a socket to reuse it for different connections, if it is possible at all.
    --Poonam.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Problems running external Win32 Multithread C-Program from Java

    hi,
    i just wrote a little java application which is calling my c-binary (a win32 multithread application written in pure ansi c) . let's call it "test.exe". i'm launching it via:
    Runtime.getRuntime().exec(cmd, new String[] { env }, dir)the program is started correctly and i get all test.exe outputs on my java console (therefor i grabbed the inputstream and errorstream of the process-object ...). so far so good.
    my problem is, that something with the multithreading seems to be wrong, when launching my test.exe from java!
    for example, i have the following line of code in my c-program (test.exe):
    WaitForSingleObject( g_hMutexREADY, INFINITE );if i launch my program as java process, this line seems to be ignored! that means, the program doesn't stop executing at this point (and is waiting for the mutex) but simply continues executing, causing the whole program to crash.
    if i run the same program directly from the winxp commandline all is working fine (that means: the threads of 'test.exe' synchronize each other correctly via the mutexes)!
    does anybody has an idea or have already had similar problems? maybe some win32 libraries are missing, could that be?
    thanks a lot.
    k4simir

    I just debugged a little bit through my c program. and it's not the multithrading stuff causing the error, but the win32 socket creation!
    my "multithreading c program" :-) is an ASR (automatic speech recognizer). it runs as socket server (on localhost) and accepts connections from clients (my java application). the client (java app) controls the ASR server (means start(), stop(), open(), close() ...). if the ASR server recognizes some user input, it will transfer it to the client for further processing.
    so far the theory. if i launch the ASR server via the window command line, the communication and the other stuff works fine. now i want my java app to launch the ASR server.
    the ASR fails, when it tries to create the socket:
    g_Vars.kServSock = socket( AF_INET, SOCK_STREAM, 0 );the error code returned by WSAGetLastError() is 10106! i didn't find this error code in the msdn! so i don't know what it means or what might be the problem.
    any ideas?
    thanks a lot!
    k4simir
    here's the full code:
    int     InitSocket( short sPortNr ) {
         int               iErr;
         SOCKADDR_IN     kMyAddr;
         iErr = StartUp();
         if( iErr != _SRC_OK ) {
              return _SRC_ERROR;
         // create server-socket:
         g_Vars.kServSock = socket( AF_INET, SOCK_STREAM, 0 );
         if( g_Vars.kServSock == INVALID_SOCKET ) {
              CleanUp();
              return _SRC_ERROR;
    int StartUp() {
         WORD wVersionRequested;
         WSADATA wsaData;
         int err;
         _DEBUGPRINT
         wVersionRequested = MAKEWORD( 2, 2 );
         err = WSAStartup( wVersionRequested, &wsaData );
         if ( err != 0 ) {
              return _SRC_ERROR;
         if ( LOBYTE( wsaData.wVersion ) != 2 ||
               HIBYTE( wsaData.wVersion ) != 2 ) {
              WSACleanup( );
              return _SRC_ERROR;
         return _SRC_OK;
    }

  • TCP/IP socket programming in ABAP

    Hi,
    Is there any method of TCP socket programming in ABAP? For example is there any function module for creating a socket for a IP address and port number. After that, is it possible to send binary/text data to a connected IP/port destination. I need such a solution because I need to send raw data (native commans) to barcode printer on our network which has a static IP address and listens incoming data through a fixed port number specified in its documentation. For a solution, I coded some .NET VB and built a small application that acts as a RFC server program which can be called by SAP according to definitions I made in SM59 (I defined a new TCP connection and it works well sometimes!). In this application, data coming from SAP are transferred to the barcode printer. This is achived by the .NET Socket class library. This solution works well but after a few subsequent call from SAP, connection hangs! SAP cannot call the application anymore, I test the connection in SM59 and it also hangs, so I need to restart the VB application, but this is unacceptable in our project.
    As a result, I decided to code the program that will send data to the printer in ABAP as a function module or subroutine pool, so is there any way to create a socket in ABAP and connect to specific IP/port destination? I searched for possible function modules in SE37 and possible classes in SE24 but unfortunately I could not find one. For example, do know any kind of system function in ABAP (native commands executed by CALL statement), that can be used for this purpose?
    I would appreciate any help,
    Kind regards,
    Tolga
    Edited by: Tolga Togan Duz on Dec 17, 2007 11:49 PM

    Hi,
    I doubt that there is a low level API for sockets in ABAP. There is API for HTTP but probably that won't help you. As a workaround you can use external OS commands (transactions SM69 and SM49). For example on Unix you can use netcat to transfer file. Your FM needs to dump data into folder and then call netcat to transfer file.
    Cheers

  • File descriptor leak in socket programming

    We have a complex socket programming client package in java using java.nio (Selectors, Selectable channel).
    We use the package to connect to a server.
    Whenever the server is down, it tries to reconnect to the server again at regular intervals.
    In that case, the number of open file descriptors build up with each try. I am able to cofirm this using "pfile <pid>" command.
    But, it looks like we are closing the channels, selectors and the sockets properly when it fails to connect to the server.
    So we are unable to find the coding that causes the issue.
    We run this program in solaris.
    Is there a tool to track down the code that leaks the file descriptor.
    Thanks.

    Don't close the selector. There is a selector leak. Just close the socket channel. As this is a client you should then also call selector.selctNow() to have the close take final effect. Otherwise there is also a socket leak.

  • Network and socket programming in python

    i want to learn network and socket programming but i would like to do this in python.Reason behind this is that python is very simple and the only language i know . 
    anybody can suggest me which book should i pick.
    the book should have following specification--
    1)not tedious to follow
    2)lots of example
    3)starts with some networking stuff and then get into codes
    thanks in advance with regards.

    hmm. well, your requirements are almost contradictory.
    Not sure about books, except maybe dusty's.
    Most python books cover at least some network programming (unless the book is topic specific).
    I use lots of python-twisted at work. I mean ALOT. I wouldn't recommend it to someone looking for non-tedious though! I also like gevent/eventlet (esp. the async socket wrappers).
    EDIT: Wow. My post wasn't really helpful at all. Sorry!
    Last edited by cactus (2010-09-04 09:16:54)

  • Socket Programing in J2ME - Confused with Sun Sample Code

    Hai Everybody,
    I have confused with sample code provided by Sun Inc , for the demo of socket programming in J2ME. I found the code in the API specification of J2ME. The code look like :-
    // Create the server listening socket for port 1234
    ServerSocketConnection scn =(ServerSocketConnection) Connector.open("socket://:1234");
    where Connector.open() method return an interface Connection which is the base interface of ServerSocketConnection. I have confused with this line , is it is possible to cast base class object to the derived class object?
    Plese help me in this regards
    Thanks in advance
    Sulfikkar

    There is nothing to be confused about. The Connector factory creates an implementation of one of the extentions of the Connection interface and returns it.
    For a serversocket "socket://<port>" it will return an implementation of the ServerSocketConnection interface. You don't need to know what the implementation looks like. You'll only need to cast the Connection to a ServerSocketConnection .

  • Socket programming usin nio package

    hello frens i m new to socket programming
    i come to know that nio packaage provides more sophisticated and efficient API to deal with socket programming issue
    I need to know where i can get tutorial about socket programming using nio pacakage

    Try google
    http://www.google.co.uk/search?q=java+nio+tutorial

  • Daemon and socket programming

    Hi,
    I have been given a new project whereby I have to:
    1) Write a class with a method that takes as an argument an xml document, communicate s with a SOAP server and return the SOAPs response (in this case a ResponseWrapper object).
    2) This then has to be implemented as a Daemon, that listens to a particular socket.
    The reason for this being is that it can be uploaded to a server, allowing a pearl program to send the XML to the Daemon, have this contact the SOAP server and then return the SOAPs response back to the pearl program.
    I am aware that this sounds unnecessarily complicated but it does have to be implemented this way.
    I have written the class and it successfully communicates with the SOAP server and returns a response, but have no idea how to implement it as a Daemon and have had no experience with socket programming.
    Could anyone point me to a tutorial or give me some pointers in how to get started?
    Thanks,

    It was an option to use a Web Service, but I was told
    that due to security issues it would take to long to
    write all the necessary checks and interceptors
    (which I know how to do), so I should implement it
    this way (which I don't know how to do); since it is
    sitting behind the firewall it would not be
    accessible for spoofing.Huh? You realize that tons of very sensitive information is transmitted all over the internet using Web Services right?
    I have had no experience
    with implementing this type of thing before, What is your level of experience then? This may be over your head. I'm not saying that sockets and daemons are advanced concepts, but I wouldn't throw a beginner into that task.

  • [Urgent]3G Socket programming

    May I use socket for 3G networks?
    I use the demo provided by the WTK2.5-Beta(NetworkDemo), it works well in the simulator. However, when I download the program to the mobile phone, it seems that the mobile phone that runs ServerSocket cannot create the socket ... all the 2 handsets use a 3G SIM card provided by a Hong Kong ISP smartTone ... What can I do?
    Please help~ provide any web page of codes, thanks very much!

    1.     We want to create a socket connection which can
    remain open and live for ever till it is closed. Is
    this possible in java socket programming?Yes, but it isn't practical in the real networking world. So your code had better be prepared to deal with network failures.
    2.     I am just wondering in order to communicate with
    the third party over the socket connection, does this
    other party requires to run something specific on
    their end? I am not able to understand how will my
    java code communicate with their server otherwise.It has nothing to do with java. Sockets send and recieve messages. The applications at either end, regardless of the language that they are written in, must handle those messages.
    3.     Can we send and receive data over the socket
    created and also is their specific format for the
    data? Yes.
    Can we send files of data over this connection?Yes. (Although I don't know why you would need to do that if you are doing credit card auths.)
    It would be great if someone can comment on these
    questions and also if possible please provide some
    code that can create socket connection.The tutorial.....
    http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

  • Can i run UDP  client and UDP  server socket program in the same pc ?

    hi all.
    when i execute my UDP client socket program and UDP server socket program in the same pc ,
    It's will shown the error msg :
    "Address already in use: Cannot bind"
    but if i run UDP client socket program in the remote pc and UDP server socket program run in local pc , it's will success.
    anybody know what's going on ?
    any help will be appreciated !

    bobby92 wrote:
    i have use a specified port for UDP server side , and for client define the server port "DatagramSocket clientSocket= new DatagramSocket(Server_PORT);"Why? The port you provide here is not the target port. It's the local port you listen on. That's only necessary when you want other hosts to connect to you (i.e. when you're acting as a server).
    The server should be using that constructor, the client should not be specifying a port.
    so when i start the udp server code to listen in local pc , then when i start UDP client code in local pc ,i will get the error "Address already in use: Cannot bind"Because your client tries to bind to the same port that the server already bound to.

  • RESTFUL Web Services vs Socket Programming Performance

    Hi guys,
    I will have an application which will have a service serving about to 30 million users/day and a mean of 5 requests/user.
    It means that there will be about 150 million requests per day. I will have two servers behind a load balancer and my clients will be both Java and C++.
    I think to implement RESTFUL Web Services but afraid of performance issues.
    Did you have a knowledge about the performances of web service and socket programming in such a high loaded project?
    Tnx.
    Ayberk

    ayberkcansever wrote:
    Hi guys,
    I will have an application which will have a service serving about to 30 million users/day and a mean of 5 requests/user.
    It means that there will be about 150 million requests per day. I will have two servers behind a load balancer and my clients will be both Java and C++.
    I think to implement RESTFUL Web Services but afraid of performance issues.
    Did you have a knowledge about the performances of web service and socket programming in such a high loaded project?It depends on the CPUs, RAM, disks, and network configurations of those servers.
    It depends on how the requests are distributed throughout the day.
    It depends on how big the requests are and how big the responses are.

  • HELP : Convert socket programming from Ipv4 to IPv6

    Hi all,
    I need help in converting my Ipv4 socket programing to Ipv6. How can I do this? I already have an Ipv4 socket programming that is working but when I tried to convert it to Ipv6 it doesn't work .
    this is my Ipv4 socket programming :
    DatagramPacket sendPacket;
    DatagramSocket sock;
    ip = jtfDIP.getText().trim();
    try{
    sock = new DatagramSocket();
    add = InetAddress.getByName(ip);
    sendPacket = new DatagramPacket(buf,buf.length,add,port);
    Please help me. How can I convert this to Ipv6. Thank you.

    Socket sock = new Socket("host");
    or
    Socket sock = new Socket("192.168.1.1");
    or
    Socket sock = new Socket("www.host.com");
    or
    Socket sock = new Socket("hhhh.hhhh.hhhh.hhhh");
    Get it? Just use whatever host, domain name, or IP you need, the underlying native code does the work - you'll never need to do anything, for the most part.

  • How to control tcp connection with java tcp socket programing ??

    Hi,
    I am connecting a server as using java socket programming.
    When server close the connection (socket object) as using close() method ,
    I can not detect this and My program continue sending data as if there is a connection with server.
    How to catch the closing connection ( socket ) with java socket programming.
    My Client program is as following :
    import java.io.PrintWriter;
    import java.net.Socket;
    public class client
      public client()
       * @param args
      public static void main(String[] args)
        Socket socket=null;
        PrintWriter pw=null;
        try
                          socket = new Socket("localhost",5555);
                          pw = new PrintWriter(socket.getOutputStream(),true);
                          int i=0;
                          while (true)
                            i++;
                            pw.println(i+". message is being send.");
                            Thread.sleep(5000);
        } catch (Exception ex)
                          ex.printStackTrace();
        } finally
                          try
                            if(pw!=null)pw.close();
                            if(socket!=null)socket.close();
                          } catch (Exception ex)
                            ex.printStackTrace();
                          } finally
    }

    I changed the code as following. But I couldn't catch the EOFException when I read from the socket. How can I catch this exception ?
    import java.io.BufferedReader;
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class client
      public client()
       * @param args
      public static void main(String[] args)
        Socket socket=null;
        PrintWriter pw=null;
        BufferedReader bufIn=null;
        InputStreamReader inRead=null;
        InputStream in=null;
        try
                          socket = new Socket("localhost",5555);
                          in = socket.getInputStream();
                          inRead = new InputStreamReader(in);
                          bufIn = new BufferedReader(inRead);
                          pw = new PrintWriter(socket.getOutputStream(),true);
                          int i=0;
                          while (true)
                            i++;
                            try
                              bufIn.readLine();
                              pw.println(i+". message is being send.");
                              System.out.println(i+". message has been send");
                            } catch (Exception ex2)
                              System.out.println(ex2.toString());
                              System.out.println(i+". message could not be send");
                            } finally
                            Thread.sleep(5000);
        } catch (EOFException ex)
                          ex.printStackTrace();
        } catch (InterruptedException ex)
                          ex.printStackTrace();
        } catch (IOException ex)
                          ex.printStackTrace();
        } finally
                          try
                            if(pw!=null)pw.close();
                            if(socket!=null)socket.close();
                          } catch (Exception ex)
                            ex.printStackTrace();
                          } finally
    }

Maybe you are looking for

  • I too need a keycode for crystal reports 2008

    As you can see by the string of emails below I have been trying to get a valid key code to install the software for two or three weeks. Why is it so difficult to use something you already paid for. This is not very customer friendly. Hi Todd, Unfortu

  • Help Regarding Exporting to Excel format Crystal Report XI SP5

    I am trying to export a report in MSExcel format but when i do so it gives me an error that the following export format is not supported or recognized ...... I am able to export into PDF, RTF and CSV (Server Side Only) formats . Here is the code i am

  • Oracle Reports blocks WLS 10.3.5.0 + Windows 2008 R2

    Hello, I am having a problem with Reports Server which blocks when OS RAM consumptions reaches a value of 10GB. (It seems to me that Forms are workling without any problem) To get better overview I will give you some more details. 1. WLS 10.3.5.0 is

  • ALV OOPS report - Need help

    Hi Friends, I just want to convert a normal alv grid report to ALV OOPS report using classes,methods and objects, can you please help me on it. *I have sent a sample ALV grid report program. REPORT  YSDB_ALV_ECC NO STANDARD PAGE HEADING LINE-SIZE 260

  • ISU_S_MOVE_IN_WLETTER_PRINT function module

    Hi, Can Anyone tell me about the usage of the FM ISU_S_MOVE_IN_WLETTER_PRINT in background mode? What are the parameters I should mandatorily export to the FM and Import from the FM? Moreover, If anyone has any study-material on ISU related FMs pleas