Listening to multiple ports(socets) for data?

I know that this topic has been covered before, but is either simplistic questions or overly complex things (that I don't understand... yet)
Here is my issue: I have data coming from two ports (TCP/IP) an array of 210 bytes and I'm not sure which port will be activated first. The data is asyncronus. So basically I want to figure out how to listen to the ports. I have this code...
import java.io.*;
import java.util.*;
import java.net.*;
public class SocketListener{
    public static void main(String[] argv){
        ServerSocket mySocket = null;
        ServerSocket mySocket2 = null;
        try {
            mySocket=new ServerSocket(12000);
            mySocket2= new ServerSocket (13000);
        catch (IOException e){
            System.err.println("error");
            System.exit(-1);
        try {
            Socket client = mySocket.accept();
            System.out.println("The server has connected to 12000\n");
            // do what I need it to do a.k.a. get data array
            client.close();
        catch(IOException e){
            System.err.println("error");
            System.exit(-1);
        try {
            Socket client2 = mySocket2.accept();
            System.out.println("The server has connected to 13000\n");
            // do what I need it to do a.k.a. get data array
            client2.close();
        catch (IOException e){
            System.err.println("error");
            System.exit(-1);
}I'm not sure if it works or not... but thats what I got. Is this the best way to go about this or is there something else that I should look up in documentation / look for examples / someone might have a link to something.
Thanks a lot!!!!
Edited by: KTLightning on Sep 12, 2007 1:25 PM

There are two issues at hand here, one being networking and the second being threading. Threading is an extensive subject and I don't want to shortchange you here, so you may want to read this tutorial if you are not familiar with Java threading concepts: http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html
That being said, if you want to concurrently listen to the sockets, you will need a thread for each socket you are listening. Otherwise you can use Java NIO, but unless you are going to be listening to many sockets at once, this complication is not necessary since the learning curve of Java NIO can be quite steep.
You might want to start out creating a new class that will handle the task of listening to a socket and retrieving the data in its own thread. You can do this by either extending the Thread class or implementing the Runnable interface. From your main class, you can then spawn as many of those objects as you need. The trick to this approach is knowing when the data has been read from the socket and stored in the object. For only two objects this is simple as you can have a hasData() method on your worker objects and then just put a loop in your main class checking to see if the condition has been met on the objects.
Here's some code fragments as an example...
public class SocketReader extends Thread ...
ServerSocket ss = null;
boolean hasData = false;
SocketReader(int port) {
ss = new ServerSocket(port);
public void run() {
ss.accept();
// do your stuff
hasData =true;
public boolean hasData() {
return hasData;
main() {
SocketReader sr1 = new SocketReader(12000);
SocketReader sr2 = new SocketReader(12000);
sr1.start();
sr2.start();
// keep looping until we have data in both
while (!sr1.hasData() && !sr2.hasData()) {
try {
Thread.sleep(100);
} catch (InterrruptedException ie) {/ do something}
} // end main
Keep in mind that this is a very simplistic example to demonstrate the concepts and would not be a good design for pretty much any other case.

Similar Messages

  • Can imapd listen on multiple ports?

    For historical reasons, we've got some multiplexors that expect to make the back-end imap connecto to port 993, and some others that want to talk to 994. Is it possible to configure imapd to listen on multiple ports?
    Thanks!

    I just realized this would be doable if the MMP would do STARTTLS to the back-end (since then I could enable STARTTLS on the default port and keep SSL on connect on the other port).
    If only.....

  • Listen on multiple ports for smtp?

    Traditionally, we've provided setup smtp to listen on an additional port to 25 for travellers who find themselves on an ISP which blocks that port. We used a line in master.cf like:
    <newportnumber> inet n - y - - smtpdproxywrite unix - - n - 1 proxymap
    This seems to make snow leopard's postfix unhappy. It also doesn't work. I'd be grateful if anybody could tell me:
    * what is or where to look for info on setting up postfix to do multiple ports? I've tried Apple docs and found nothing and only old-style in postfix docs -- though I could be missing something obvious as always.
    * is this the modern and preferred way to get around the blocked port 25 problem or is it better to do some fancy-schmancy port redirection eg at the firewall to map multiple ports on to port 25 for postfix?
    thanks and allbests,

    In the past I've used the following with great success. Add the following line to /etc/postfix/master.cf file:
    2525 inet n - n - - smtpd
    Stop and start the mail service. Then test with telnet to ensure that the port is responding. Sadly, this still appears to be the best way, sans the use of a VPN, to get around ISP blocking.
    Obviously port 25 needs to be open to receive mail. But instead of opening additional port in the firewall, you could drive all users to VPN.
    I just tested the above line in 10.6.1 and it is responding.
    Hope this helps

  • SocketServer Listen on Multiple Ports

    What is the optimal way to have a SocketServer listen on more than one IP/port combination? I'm looking for various ways of doing this including a quick and easy way and the best-practices way.
    Thanks.

    There is no way to 'have a SocketServer listen on more than one IP/port combination'. A SocketServer can only listen at one port. You need multiple SocketServer objects, and you should use multiple threads executing accept loops.

  • Multiple port opened for one db connection.

    My java standalone server connects to sql server via MS sql JDBC driver(v 2.2). I saw so many port in Time_wait state to the db server in netstat. I did some search on the internet, found that this the nature of TCP/IP protocol. and we can live with it without modifying Windows config.
    however, I noticed on my side, there are two ports involved for each database connection. I think this is one of the reasons I have so many ports in Time_wait state.
    To me, it seems like the request to db server is done on one port, the response from db server is done on another port. is this implemented on JDBC driver layer or on sql server?
    please help !!!

    I saw so many port in Time_wait state to the db server in netstat. This suggests that you are not using any type of connection pooling, but instead are opening and closing connections pretty quickly, although it depends on what you mean by "many"; 10 or 100 might be a good number for a busy system, depending on your application. On some operating systems under high load, it could potentially be a problem if you are getting into many hundreds or thousands, but other issues usually drive people to using connection pools long before this issue would.
    however, I noticed on my side, there are two ports involved for each database
    connection. I think this is one of the reasons I have so many ports in Time_wait state.Not really. That might double the number, but the real reason is a lot of connection closes (real connection closes, not closes on a pooled connection).
    To me, it seems like the request to db server is done on one port,
    the response from db server is done on another port.
    is this implemented on JDBC driver layer or on sql server?That is totally up to the driver vendor; there's nothing you can do about it.
    please help !!!I'm not sure what you're problem really is - you might be worrying about something that isn't a problem. Is something bad happening that you're trying to fix, or did you just notice these expiring ports and start worrying about them?

  • Multiple Sound Card for data acquisition gives read buffer error

    I am using 6 usb based sound cards for voltages and currents mearuments of a three phase delta system.. Hardware is working well. but in labview when i use builtin Input=>sound box for data acquisition it also works well upto 4 inputs... but when i use more i.e. 6 it starts giving error "cannt perform action, read buffer is full" some thing like this... som times it goes to "not responding"...i have tried to find the solution and found in another post of this fourm to varry the sampling rate... i did it upto 96000 that is maximum ... but still problem is same...i need to know, how to manually increase the read buffer. if not possible then.. is there any way that labview stop giving any type of error during simulation?

    thnx i hv solved that problem ... now there is another problem... i am getting all my signals in computer but problem comes when i use phase detector. it keep on showing different values in phase measurement block.. how can i manage the signal with correct phase. i cannt send code cz it has many VIs and they are spread in computer. so i am pasting come photos that are showing different. look in picture...it is from same signal and the phase is different..
    Attachments:
    Capturexcvxccxvxcvcxvvxcvxcv.JPG ‏11 KB
    Capturexcvxcvxcvxcv.JPG ‏11 KB

  • Netbeans 6.1 SMS NON-Brute force ability listen to multiple ports

    First of all, my appologies for being a nubie coming from Mobile6. The company I slave at is migrating from MS Mobile to j2me!!! I am porting a code segment that listens to all incoming/outgoing SMS text messages and logs the messages into another java contact applet for our sales department. Our company policy(I cannot change) allows the sales department to use any/multiple SMS packages and install onto the device.
    Based on my understanding of the (MessageConnection)Connector.open("sms://" foo); I must include a port address to listen in on. Is there a NON-brute forced methodogy to poll "active" ports the device is using to send/recieve SMS text message?
    /dz
    Little Rock, AR.

    db,
    I was reading a blog by Bill Day [http://weblogs.java.net/blog/billday/archive/2004/02/midp_push_using.html]
    regarding MIDP Push; A paragraph jumped at me, it was "...
    Whichever network(s) you're application will be using, you need to find out what protocols they allow inbound to handsets. At the least, most GSM carriers will allow SMS (since they use SMS for short text messaging). Assuming your network does support SMS, from the server part of your application you would need to generate an SMS message directed to the port you bound your MIDlet to in its static or dynamic push registry settings. Assuming the network passes the SMS as expected, your MIDlet should be awakened when the SMS arrives in the handset..."
    Either I'm not understanding your reponse, the info in this blog is incorrect or I must include a port address as part of the open method of the Connector. Still confused.
    /dz

  • One weblogic instance listening to multiple ports

    I'd like to run weblogic with its http subsysten listen to port 80.
    Any other service should listen to port 7001.
    Is it really impossible to let weblogic do this?
    Are there any plans to implement such a feature?
    Which alternatives do exist?
    TIA
    klaus

    No, it is impossible.
    Alternatives: use IIS/Apache/NES to listen to port 90, and use weblogic
    plugin to proxy request to WLAS (7001).
    Still, you can use one WLAS listent to port 80, and use HttpClusterServlet
    to proxy requests to another WLAS (7001)
    Cheers - Wei
    Klaus Pittig <[email protected]> wrote in message news:[email protected]..
    I'd like to run weblogic with its http subsysten listen to port 80.
    Any other service should listen to port 7001.
    Is it really impossible to let weblogic do this?
    Are there any plans to implement such a feature?
    Which alternatives do exist?
    TIA
    klaus

  • Always on availability listener with multiple IP addresses for SharePoint 2013

    Hello
    I think theres something I'm missing about AG listeners. My test config is 1 SharePoint WFE & 2 SQL servers configured in an AAG.
    WFE, SQL1 & SQL2 servers are all on the same subnet.
    On the WFE, I configured an alias called SP15 to be used for the SQL  servers. If I failover from SQL1 to SQL2 I just need to change where the alias is pointing on the WFE. So why do I need a listener? This works fine, albeit manually.
    I have read on some posts that an automatic failover process is possible. This sounds ideal. How can I add a 2nd IP address to the listener when both SQL servers are on the same subnet? The GUI doesn't seem to allow this.
    TIA
    Dermot C

    In addition to what David has already mentioned, the Availability Group Listener Name can be used to replace the SQL Alias that you've created on your WFE. This makes it easier for high availability and disaster recovery but is also a great approach for
    migrating to a better hardware because the connection to the database is abstracted by the listener name.
    Edwin Sarmiento SQL Server MVP | Microsoft Certified Master
    Blog |
    Twitter | LinkedIn
    SQL Server High Availability and Disaster Recover Deep Dive Course

  • Can Ideapad Lynx k3011 micro USB port use for data communicat​ion?

    Greetings,
    I would like to connect on one end an VAG-Com USB dongle (http://www.ross-tech.com/vag-com/hex-usb+can.html) via a Micro USB adaptor to the tablet and the CAN bus to my car on the other end to turn some car features on and off. Can the Micro USB port on the tablet be used as communication device to achieve this?
    Thanks,

    Just check ebay or http://www.parts4repair.com/brands/Sony.html
    "I'd rather be hated for who I am, than loved for who I am not." Kurt Cobain (1967-1994)

  • Select Multiple into array for data insertion

    I have a form that contains a menu/list that allows multiple selections. The list is bound to a dynamic source with label = to a name and value = to the names record ID. The code DW CS4 generates is:
    <select name="vVol_id" size="20" multiple="MULTIPLE" id="vVol_id">
    <?php
    do { ?>
                    <option value="<?php echo $row_rsGetStaff['vol_id']?>"><?php echo $row_rsGetStaff['full_name']?></option>
                    <?php
    } while ($row_rsGetStaff = mysql_fetch_assoc($rsGetStaff));
      $rows = mysql_num_rows($rsGetStaff);
      if($rows > 0) {
          mysql_data_seek($rsGetStaff, 0);
          $row_rsGetStaff = mysql_fetch_assoc($rsGetStaff);
    ?>
    </select>
    What additional code do I need to get the selected items into an array that can be 'foreach'd' to insert the selections into another table when the submit button is clicked? This one has been driving me nuts.

    You just need the square brackets, something like: <select name="vVol_id[]"
    vVol_id will then be an array if items are selected.
    Ed

  • Multiple Selection Boxes for Data

    Hello all,
    I need to create a dashboard that will allow me to drill down by two parameters.  For example:
    I need to see the country in this example USA and then a second critera would be the states.
    So I would want to be able to select USA in one combo box potenially and see the totals and then select a specific state in a second combo box and see those totals.
    I would then want to do south america and those countries.  So South America and then Brazil, mexico, ect.
    Any feedback or ideas.

    HI Jeffrey....
    U can try with the filter option for drilling down to your actual content. For clear picture go through the following link.
    http://visualbis.com/blogs/multi-select-combo-box-for-sap-businessobjects-dashboards-xcelsius/
    Regrads,
    P.Gowri

  • Listening multiple ports

    is there anyway a serversocket can listen to multiple ports?like the the serversocket can listen ports between 1 to 1024?thanks!

    no methods that i know of. except to create an array of serversockets but pass the handling of sockets to a centralized location.

  • Question: one weblogic server listening on several port

    can i start one weblogic server that listening on several port, one for
    different application?
    for example,
    7001 for general user, and
    7005 for admistrators and ask for two way authentification?
    can i do this? or do i have to start two weblogic instance? does that
    violate it's license for one computer and one ip address?
    thank u.

    Ummm.. how would this help security? If I want to bypass authentication, I just go to the unprotected port.
    I don't think you can listen to different ports in the same instance
    . You can listen to different IP addresses in the same instance.
    WL is licensed by CPU so this would not cost any more to license.
    mike
    "Gong Wenxue" <[email protected]> wrote:
    can i start one weblogic server that listening on several port, one for
    different application?
    for example,
    7001 for general user, and
    7005 for admistrators and ask for two way authentification?
    can i do this? or do i have to start two weblogic instance? does that
    violate it's license for one computer and one ip address?
    thank u.

  • Separate listener for Data Guard

    I am setting up a best practice about using a dedicated listener for Data Guard. The idea is to maintain full functionality of Data Guard while application team is requesting to bring down listener service (according to business requirement). Need your opinion on these:
    1. I understand that there may be a very little chance when listener is required by Data Guard, but I find it no harm to do this. Do you agree with me?
    2. In RAC environment, we can only have 1 VIP to be used in listener.ora. I am thinking of using same IP but different port numbers for different listener. Any better idea than this?
    Many thanks

    It is never a bad practice to use separate listeners at the primary and at the Standby for Data Guard's use. A listener at the standby is required by Data Guard to make a connection to that standby. A listener at the Primary is required for Data Guard to make a reverse connection from the Standby to the Primary for some kinds of Gap resolution (missing log file the the Primary thinks it already sent or a corrupted log file etc). And of course, when you switch roles.
    To answer the second question could you please tell me what version of Oracle you are using and if you plan on using the Data Guard Broker or not?
    Thanks.
    Larry

Maybe you are looking for

  • Adobe Media Encoder Error with MPEG2 Formats [../../src/Command.cpp-2519]

    I am trying to use some of my presets using MPEG2 format and it is giving me this error: [/Volumes/BuildDisk/builds/ame602_mac/main/app/frontend/prj/mac/../../src/Command.cpp-251 9]. I try the system presets that use MPEG2 and I get the same error. I

  • Error in invoking target 'install' of makefile ...ctx/lib/ins_ctx at instal

    During link steps at installing 11gR2 on OEL5 I got: Exception String: Error in invoking target 'install' of makefile '/oracle/112/ctx/lib/ins_ctx.mk'. See '/oracle/oraInventory/logs/installActions2009-10-09_09-21 -45PM.log' for details. Exception Se

  • How do I remove my own copyright from a photo

    How do i remove my own copyright and or watermark from a photo please

  • Error message for mac?

    I have just purchase and started to use Photoshop Elements 9 for Mac. Whenever I attempt to open a photo saved with the .psd extension I get the error message: An error occurred during Apple event processing.  -43 I don't have this problem with the .

  • Switching back to iTunes UK from abroad

    I live in Ireland having moved over from the UK. I had a UK iTunes account which I cancelled and opened up a new account in order to purchase from an Irish bank account. I still have a UK bank account and wondered if it were possible to switch back t