Client/Server UDP question

Hi,
I am writing a server program which both sends and receives UDP messages to various clients.
What I want to do is both send and receive on the same port. I'd like the receiving to be done on the same thread (and therefore on the same socket). However I'd like the sending to be done in multiple threads (1 per client).
The problem is, I don't think I can use the same socket object to send to all of the clients. I'm thinking there would be collisions/problems with the multiple threads sending on the same socket.
However, if I create multiple sockets for sending, and one socket for receiving (all bound to the same port), is there a way to tell the "sending" sockets to only send (i.e., not receive)? Or is this automatically done simply because I never do a socket.receive on those sockets? Or do I need to pick a different port for sending rather than receiving?
What I want to avoid is listening to the port on my "listen" socket, but having that data show up on one of my "send" sockets (and therefore never seen, because I don't do a socket.receive()).
I've looked in the forums/tutorials for this, but nothing I've seen addresses needing to send from multiple threads, or needing to have listening on a separate thread (which I need to do to prevent having the receive() block the send()). Please bear with me if this is a stupid question; I'm new to network programming, especially UDP.
Any help would be greatly appreciated!

it shouldn't be a problem to send from multiple threads and receive on another thru the same UDP socket. If you want to send from a different socket, that's fine too... except that the other side will need to know to send responses back to your receiving socket (port) and not the "source" of the packets they receive.
I'm not sure you can mark the socket for send or receive only, but it really doesn't matter. Just don't read from the sending one or write to the receiving one. An incoming packet isn't going to block an outgoing packet, or an outgoing packet isn't going to push an incoming packet out of the way. The pipe analogy for socket connections isn't so literal like a real pipe where water could only really go one way.
It's the threads that would block on while waiting for input, which is why you need separate threads, but not necessarily separate sockets.

Similar Messages

  • Client server applet question

    Hello I have a client and server program on computer a and computer b.
    I want a webpage with a java applet.
    I want that if I push a button in the client the java applet gets a message.
    I want that the server looks for changes in the applet and when there is a change the server does something.
    I have a program where the client and server communicate with eachother but how can I make a program like I want?
    How can I send a message to the applet(on a webpage) from the client and how can I look at the applet with my server??

    Aplet runs on client side (in other words on PC which is used to view page). On server side it is stored only as any other kind of file. To be able to create "client-server" solution you have to be able to run code also on server machine. I did not found any free hosting server which allows to run java. But in many cases they allow to use PHP which runs enteirly on server side. Check for this - it may be right solution for you.

  • Client/Server application question

    Hey everyone,
    I am trying to exercise on a client/server application. My client application is similar to this one [http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/Code/SocketClient.java]. However this client works like this: it sends text through socket -> receive response from server. I am trying to find a way so that the client can receive and process messages from the server asynchronously. That is the server can send messages anytime (not just as a response to the client) and the client should always be able to receive messages from the served at any time, and not just after it sent something. I believe that multithreading would be the answer, listening to the output stream and sending through the input stream should be run in parallel, but I can't find a way to implement it. Your help is appreciated. Thank you.

    I knew that :-) but how exactly?
    How do I translate this code into two runnable classes which will communicate with the original class and its gui?
    //Send data over socket
              String text = textField.getText();
              out.println(text);
           textField.setText(new String(""));
    //Receive text from server
           try{
           String line = in.readLine();
              System.out.println("Text received :" + line);
           } catch (IOException e){
          System.out.println("Read failed");
                 System.exit(1);
      }

  • Client/Server connection question

    I am trying to understand some basic connectivity tricks between Client and Server.
    I saw my friend doing stuffs like, query google.com with certain keywords, and present the return results on another webpage or program using jsp. I have no idea how he did that, and I wonder if anyone here is familiar with such tricks.
    Edited by: ttback on Dec 3, 2007 4:06 PM

    To access a specific search thing you can use URL and URLConnection classes like:
    String search_query; //input it...
    URL url = new URL("http://www.google.com/search?hl=en&q=" + search_query + "&btnG=Google+Search");
    URLConnection urlc = url.openConnection();
    //read from urlc
    //print the result...

  • Client server basic question

    I have a web service that returns byte arrays to the client. First a byte array is returned and the server gets the acknowledgement, then the next byte array is sent and so on. But I don't have much idea how to implement it. How can I resume from where I stopped at the server side? Can anyone give me some idea so that I can proceed?
    Thanks.

    Thanx for your reply!
    So if I have a relatively small number of clients that do a lot of data processing, then the following scenario would be ok to do:
    - a (rich) client connects to the J2EE server with some EJB call.
    - the server creates a queue for that client and that session.
    - the client creates a MessageConsumer for that queue.
    - the client sends a message based data request to a server queue.
    - a MDB processes that data request and sends a reply message to the clients "session queue"
    Would that be ok?

  • Client Server Socket question!

    Hello all,
    how are ye.
    I would like to ask a question.
    I would be graterful for any suggestions relating to my query.
    i am creating a program that needs to communicate over a network
    it has two parts
    P1) sends request to the other program mainly about account information and
    also updates.
    P2) the second part among other things listens for messages on a port from Program One.
    but also must be able to interface with the user who is using Program Two, the user should be able
    to view account info update delete search etc.
    my problem is how will i get the second program todo both operations do i need
    to create another thread that listens and if i do this. will i be able to
    like add info to a database from this thread.
    Mainly i need suggestion as to how i should implement a scenario like the above.
    I am sorry if i havent spelled out my problem in a clear manner.
    Very grateful for any assistance.
    Thank you all :-)

    http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/socket.html
    That should help you out.

  • UDP client/server

    Im trying to connect to a server from my client useing UDP. My partner has the server but im not able to see it at the moment. I have the client that is trying to reach it. Here is the code i use:public Connect(String serv_addr){
              try{
                   skt = new DatagramSocket();
                   server = InetAddress.getByName(serv_addr);
                   byte[] connectData = new byte[128];
                   connectData = sentance.getBytes();
                   sendPacket = new DatagramPacket(connectData, connectData.length,
                             server, 4525);
                   skt.send(sendPacket);
                   System.out.println(new String(sendPacket.getData()));
              catch(IOException e){
                   System.err.println(e);
         }When i run it, i cannot connect and my partner tells me the server is running. Without seeing the Server code and assuming it works properly, does my code look right? The last line in the try statment, Syste.out.ptintln is justing being used for testing.
    Thanks in advance

    and is there a firewall in the way? If so it won't probably won't forward UDP traffic on that port unless it's been told to, and you won't get an exception.
    And some possibly silly questions:
    a. are you sure it's a UDP server?
    b. are you aware that UDP is an unreliable transport?
    You could also try to connect() the datagram socket to that target address before you send. That way if the target is unreachable you will at least get an exception.

  • Question, in a client server implemention

    Question, in a client server implemention using only basic sockets and datagrams, what happens if a method is being called at the server side while the same method is already being called/running for another client?
    Example:
    Client 1 calls Method 1 at Server Side. Method 1 runs.
    Client 2 calls Method 1 at Server Side. Method 1 is still running for Client 1. Does it create another Thread and runs for Client 2? Or do I have to implement a seperate Thread for each Client myself?

    Thanks!
    Don't want to start a new thread so might as well ask this here,
    Is there a way to pass or at least update the value of a variable from the outside into a Thread that is running? And this value needs to be seen and be the same for all Threads.
    I am thinking of creating new a class that to hold the value I want to update, and passing an object of the class in to the Threads before they runs. Since objects hold reference to the location of the actual object or something like that; people always get worked up over this if I phrase this incorrectly, but I think I got the point across, so that's okay. If I change the value of the object at runtime in the main method, like assign it with a new value according to user input. All the Threads will get the new value right?
    Something like that.
    public class valueToUpdate {
    String value;
    public valueToUpdate(String value) {
    this.value = value;
    public String getValue() {  
    return value;  
    public class Main {  
    public static void main(String[] args) {  
    String str = "abc";  
    valueToUpdate vTU = new valueToUpdate(str);  
    ThreadClass tc1 = new ThreadClass(vTU);  
    Thread thread1 = new Thread(tc1).start();  
    ThreadClass tc2 = new ThreadClass(vTU);  
    Thread thread2 = new Thread(tc2).start();   
    public class ThreadClass implements Runnable {  
    valueToUpdate vTU;  
    public ThreadClass(valueToUpdate vTU) {  
    this.valueToUpdate = valueToUpdate;  
    public void run() {  
    System.out.println(valueToUpdate.getValue());  
    }Okay, something like that. I know I need to add in a TimerTask for ThreadClass too for it to run for a certain period. But if I were to ask for user input at the main method while the TimerTask in running, and I change the value of vTU, will the output for both Threads be changed to the value of the user input?
    Or is there a better way to do it?

  • Forms 6i client/server questions

    Hi, I have three questions:
    1) Is Patch 17 for Forms6i cumulative? (we have patched up to patch 13)
    2) After applying patch 17 do we need to recompile all of our forms?
    3) We are connecting from 6i client/server forms to a 10.1.4 database, is there a recommended Oracle client? (we are very behind and still running a very old version and I'm trying to get information to move forward)
    Thanks.

    Patch 17 is designed for the 10g database. There is no hint, that a 9i-db is better than a 10g. Use 10g.
    I always recompile all (!) libs, menues and forms after installing a new patch. It's better to do that once, than to search for failures, that result from patching.
    try it
    Gerd

  • Reliable UDP client/server sample

    I need a reliable UDP client/server sample which uses ack,timeout,sequence number, etc. Client and server are different computers in the same network and I need to send a file >10Mb. Where can I find this kind of example? It is required for a project at my university.
    Thanks.

    Can't you use TCP? It already is reliable, has better performance than simple UDP+ACKs (unless you too implement sliding windows), and is a good network citizen (unless you too implement congestion control). Why reinvent the wheel?
    Unless of course your assignment is "reimplement TCP using UDP" in which case you can find the "example" by writing it.

  • JMS architecture question for fat client/server.

    Hi. Is JMS suitable for fat client-server architecture where a certain number of fat client applications (like a few hundreds) open connections directly to the JMS provider? Is it going to have scalability problem when the number of connections grow?

    Depending on your JMS provider, this may be a very suitable architecture. The Sun MQ JMS Cluster was architected exactly for this problem. If the number of connections onto a single broker becomes too much of a burden for this broker, it can be put into an MQ cluster and share the number of connections. Of course, the number of connections a broker can handle will be totally dependent on the resources available to it. OS, CPU, memory, other applications running on the same machine, etc....
    TE

  • Need Help for client - server - client question [Sockets]

    Hi
    I have read the http://java.sun.com/docs/books/tutorial/networking/sockets/index.html tutorial and made this Knock Knock Application.
    But now, I want that one client can view all the other clients which are connected to the server, and interract with a selected cleint over the server (client - server - client).
    But I have no idea how to build such a registration concept?
    A concrete hint (or link) how to realise this would be very helpful. I searched all the internet for examples, but I dont found a simple example.
    Thanks in advance
    greeds

    wSam,
    It appears that Sun considers RMI to be simpler, although less efficient than the alternative:
    http://java.sun.com/developer/technicalArticles/ALT/sockets/
    This article also talks about object serialization, which I am a fan of. Suppose that you want to send a data structure containing lots of information (like all connected users). You can actually pass an object (rather than text) across the network using ObjectOutputStream and receive it on the other end with ObjectInputStream. You might create your own Command class for passing objects between the client and server instead of using RMI. The Command class might hold flags that indicate which method should take place on the remote machine (i.e. send chess move command).

  • Client/Server to Web-Based application Conversion

    Hi! Everyone,
    I have couple of questions for you guys.
    Our Client had recently upgraded Forms 4.5 to 6i to move from Client/Server based application to Web based application.
    They are using Forms Server 6i Patch Set 1, OAS 4.0.8.1, Windows NT Service Pack 5 and Oracle 7.3. They are facing the following error every now and then, when they run the forms,
    "FRM-92100: Your connection to the server was interrupted. This may be the result of a network error or a failure on the server.You will need to re-establish your session."
    Please let me know what might be causing the above error. The only problem i can think about might be Oracle 7.3. If i am right only Oracle 8 and above supports Forms 6i.
    Can anyone let me know some tips and/or techniques to upgrade Forms 4.5 to 6i. If there are any important settings/steps which we might have over looked during the upgrade, please list them.
    Any kind of help is greatly appreciated.
    Thanks,
    Jeevan Kallem
    [email protected]

    Most of the code is use with no changes at all.
    See otn.oracle.com/formsupgrade
    Regards
    Grant Ronald

  • Client/Server in one program (using multiple threads)?

    Is there some examples out there of how to use a client and server in a single program using separate threads? Also, is it possible to start a third thread to control the packets, such as drop a random or specified number of packets (or match on specific data in a packet)?

    Just trying to have a client send udp packets to a server (all on the same machine running from the same program) and want to be able to drop packets coming from the client side to the server side.
    E.g.,
    Here's an example that I found here: http://compnet.epfl.ch/tps/tp5.html
    import java.io.<strong>;
    import java.net.</strong>;
    import java.util.<strong>;
    /</strong>
    * Server to process ping requests over UDP.
    public class PingServer {
         private static double lossRate = 0.3;
         private static int averageDelay = 100; // milliseconds
         private static int port;
         private static DatagramSocket socket;
         public static void main(String[] args) {
              // Get command line arguments.
              try {
                   if (args.length == 0) {
                        throw new Exception("Mandatory parameter missing");
                   port = Integer.parseInt(args[0]);
                   if (args.length > 1) {
                        lossRate = Double.parseDouble(args[1]);
                   if (args.length > 2) {
                        averageDelay = Integer.parseInt(args[2]);
              } catch (Exception e) {
                   System.out.println("UDP Ping Server");
                   System.out.println("Usage: java PingServer port [loss rate] [average delay in miliseconds]");
                   return;
              // Create random number generator for use in simulating
              // packet loss and network delay.
              Random random = new Random();
              // Create a datagram socket for receiving and sending UDP packets
              // through the port specified on the command line.
              try {
                   socket = new DatagramSocket(port);
                   System.out.println("UDP PingSever awaiting echo requests");
              } catch (SocketException e) {
                   System.out.println("Failed to create a socket");
                   System.out.println(e);
                   return;
              // Processing loop.
              while (true) {
                   // Create a datagram packet to hold incoming UDP packet.
                   DatagramPacket request = new DatagramPacket(new byte[1024], 1024);
                   // Block until the host receives a UDP packet.
                   try {
                        socket.receive(request);
                   } catch (IOException e) {
                        System.out.println("Error receiving from socket");
                        System.out.println(e);
                        break;
                   // Print the received data.
                   printData(request);
                   // Decide whether to reply, or simulate packet loss.
                   if (random.nextDouble() < lossRate) {
                        System.out.println("   Reply not sent.");
                        continue;
                   // Simulate network delay.
                   try {
                        Thread.sleep((int) (random.nextDouble() * 2 * averageDelay));
                   } catch (InterruptedException e) {}; // Ignore early awakenings.
                   // Send reply.
                   InetAddress clientHost = request.getAddress();
                   int clientPort = request.getPort();
                   byte[] buf = request.getData();
                   DatagramPacket reply = new DatagramPacket(buf, buf.length,
                             clientHost, clientPort);
                   try {
                        socket.send(reply);
                   } catch (IOException e) {
                        System.out.println("Error sending to a socket");
                        System.out.println(e);
                        break;
                   System.out.println("   Reply sent.");
          * Print ping data to the standard output stream.
         private static void printData(DatagramPacket request) {
              // Obtain references to the packet's array of bytes.
              byte[] buf = request.getData();
              // Wrap the bytes in a byte array input stream,
              // so that you can read the data as a stream of bytes.
              ByteArrayInputStream bais = new ByteArrayInputStream(buf);
              // Wrap the byte array output stream in an input stream reader,
              // so you can read the data as a stream of characters.
              InputStreamReader isr = new InputStreamReader(bais);
              // Wrap the input stream reader in a buffered reader,
              // so you can read the character data a line at a time.
              // (A line is a sequence of chars terminated by any combination of \r
              // and \n.)
              BufferedReader br = new BufferedReader(isr);
              // We will display the first line of the data.
              String line = "";
              try {
                   line = br.readLine();
              } catch (IOException e) {
              // Print host address and data received from it.
              System.out.println("Received echo request from "
                        + request.getAddress().getHostAddress() + ": " + line);
    }I'm looking to do the "processing loop" in a separate thread, but I'd also like to do the client in a separate thread
    So you're saying, just put the client code in a separate class and start the thread and that's it? As far as the packet rate loss thread, is this possible to do in another thread?

  • Looking for a client/server that supports multiple protocol and delivery

    Hi all, I don't know if this the right place to ask my question,here it goes.
    I am looking to develop a client-server that supports multiple protocols such as HTTP, HTTPS etc. I am looking for a framework( i don't know if that is correct or I need some kind of web-service (soap etc)) that would manage connection, security etc. I would like to like to devote most of my time in developing business objects with multiple delivery mechanism such as sending serilized java objects, xml message or soap message, or in some case JMS message as well. So I need a client server that can come in via TCP/IP or HTTP or anyother industry standard protocol and I should be able to service him with pub/sub model and also request/response model as well.
    I don't know if I had explained what I need, I would like to know what technologies I should be evaluating and which direction I should be heading... Also the server I'm developing should be free of Java constraints if needed...
    Also this service is not webbased service as now but if need arises I should have a flexibilty to make them web enabled in future. Also I would like to work with open source webservers or appservers if I need

    Inxsible wrote:I installed i3 - along with the i3status - which I still have to figure out. I am liking what I see as of now. It reminds me of wmii -- when I used it way back when. However I do not like the title bar. I would much rather prefer a 1 px border around the focused window.
    "i3 was created because wmii, our favorite window manager at the time, didn't provide some features we wanted (multi-monitor done right, for example), had some bugs, didn't progress since quite some time and wasn't easy to hack at all (source code comments/documentation completely lacking). Still, we think the wmii developers and contributors did a great job. Thank you for inspiring us to create i3. "
    To change the border of the current client, you can use bn to use the normal border (including window title), bp to use a 1-pixel border (no window title) and bb to make the client borderless. There is also bt  which will toggle the different border styles.
    Examples:
    bindsym Mod1+t bn
    bindsym Mod1+y bp
    bindsym Mod1+u bb
    or put in your config file
    new_window bb
    from: http://i3.zekjur.net/docs/userguide.html (you probably already found that by now )

Maybe you are looking for