Client / Server Socket Communication - Should use 2 ports?

If we have a client server architecture using a socket based connection, should there be 2 serperate sockets? One dedicated to sending and one dedictated to receiving? What happens if both the client and server both send at the same time? How does that get handled? Does one of the messages get dropped? Thanks...

There are of course reasons you might want to use two sockets.
For instance security. One socket is encrypted and the other isn't. Or because the server initiates a confirmed port connection back it verifies the IP.
Or because the main socket is used for control and the second one is used for data. That way the client can tell the server to pause or make other adjustments in the data while the data is still flowing.

Similar Messages

  • Client/server socket based application

    hi does anyone have example of client/server socket based application using Spring and Maven
    where application do the following
    Client sends a request with a path to any file on the server
    „h Server reads the file and responds back with the content
    „h Client outputs the content to the console
    am trying to follow this
    http://www2.sys-con.com/itsg/virtualcd/java/archives/0205/dibella/index.html
    http://syntx.io/a-client-server-application-using-socket-programming-in-java/
    am using java 6

    i have attempt code but i wht to do the following
    client/server socket based application that will read the content of a file and stream the content of the file to the client. The client must simply output the content of the file to the console using System.out. The client must be able to run in a standalone mode (non-network mode) or in a remote mode.
    Additionally the client must be designed in a way that i can print the output to a console but must be interchangeable where if requirements change i can persist the response to file or persist the response to a database.
    /* Server.java*/
    ///ifgetBoolen= true then...
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.sql.*;
    public class Server
        static String array[][];
        // STEP 1 a1  
        // Server socket
        ServerSocket listener;
        // STEP 1 a2 Client connection
        Socket client;
        ObjectInputStream in;
        ObjectOutputStream out;
        public void createConnection() throws IOException
                System.out.println("\nSERVER >>> Waiting for connection.....");
                client = listener.accept();
                String IPAddress = "" + client.getInetAddress();
                DisplayMessage("SERVER >>> Connected to " + IPAddress.substring(1,IPAddress.length()));
          public void runServer()
            // Start listening for client connections
            // STEP 2
            try
                listener = new ServerSocket(12345, 10);
                createConnection();
                  // STEP 3
    //              processConnection();
            catch(IOException ioe)
                DisplayMessage("SERVER >>> Error trying to listen: " + ioe.getMessage());
        private void closeConnection()
            DisplayMessage("SERVER >>> Terminating connections");
            try
                if(out != null && in != null)
                      out.close();
                    in.close();
                    client.close();                
            catch(IOException ioe)
                DisplayMessage("SERVER >>> Closing connections");
        public static void define2DArray(ResultSet RS, int Size)
            try
                ResultSetMetaData RMSD = RS.getMetaData();
                DisplayMessage("SERVER >>> Requested arraySize: " + Size);
                if (RS.next())
                    array = new String[Size][RMSD.getColumnCount()];
                    for (int Row = 0; Row < Size; Row++)
                        for (int Col = 0; Col < RMSD.getColumnCount(); Col++)
                            array[Row][Col] = new String();
                            array[Row][Col] = RS.getString(Col+1);
                            DisplayMessage(array[Row][Col] + " ");
                        RS.next();
                else
                    array = new String[1][1];
                    array[0][0] = "#No Records";
            catch (Exception e)
                DisplayMessage("SERVER >>> Error in defining a 2DArray: " + e.getMessage());  
        public static void DisplayMessage(final String IncomingSMS)
            System.out.println(IncomingSMS);
    //client
    * @author
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class ClientSystem
        static Socket server;
        static ObjectOutputStream out;
        static ObjectInputStream in;
        static String Response[][];
        static boolean IsConnected = false;
        static int Num = 0;
        public static void connectToServer() throws IOException
            server = new Socket("127.0.0.1", 12345);
    //        server = new Socket("000.00.98.00", 12345);
            String IPAddress = "" + server.getInetAddress();
            DisplayMessage("\nCLIENT >>> Connected to " + IPAddress.substring(1,IPAddress.length()));
        public static void getStreams() throws IOException
            out = new ObjectOutputStream(server.getOutputStream());
            out.flush();
              in = new ObjectInputStream(server.getInputStream());
              IsConnected = true;
              DisplayMessage("CLIENT >>> Got I/O streams");  
        public static void runClient()
            try
                connectToServer();
                getStreams();
                  DisplayMessage("CLIENT >>> Connection successfull....\n");
                  DisplayMessage("CLIENT >>> Want to talk to server");
            catch (IOException ioe)
                System.out.print("."+Num);
                Num++;
        public static void closeConnection()
            try
                out.close();
                in.close();
                server.close();  
            catch(IOException error)
                DisplayMessage("CLIENT >>> Could not close connections");
        public static void Start()
            System.out.print("\nCLIENT >>> Attempting connection.....");
            try
                IsConnected = false;
                while (IsConnected == false)
                    runClient();
                    if (IsConnected == false)
                        Thread.sleep(100);
            catch (Exception e)
                DisplayMessage("CLIENT >>> Attempting connection.....");
        public static String sendSMS(String sms)
            Response = new String[0][0];
            try
                DisplayMessage("CLIENT >>> " + sms);
                out.writeObject(sms);
                out.flush();
                Response = (String[][])in.readObject();
                DisplayMessage("CLIENT >>> Waiting for server to respond...");
                for (int Row = 0; Row < Response.length; Row++)
                    System.out.printf( "_SERVER >>> \t");
                    for (int Col = 0; Col < Response[Row].length; Col++)
                        //DisplayMessage( "_SERVER >>> " + Response[Row][Col] + " ");
                        System.out.printf( "%s\t", Response[Row][Col]);
                    System.out.println();
                DisplayMessage("CLIENT >>> Query processed successfully....\n");
            catch(ClassNotFoundException cnfe)
                DisplayMessage("CLIENT >>> Class not found for casting received object");
            catch(IOException ioe)
                reConnect();          
            catch (Exception sqle)
                DisplayMessage("CLIENT >>> Error sending query ??? " + sqle.getMessage());
            return "transmission successfull";
        public static void reConnect()
            try
                DisplayMessage("CLIENT >>> Connection was lost. Trying to reconnect...");
                closeConnection();
                Thread.sleep(100);
                IsConnected = false;
                while (IsConnected == false)
                    runClient();
                    Thread.sleep(200);
            catch (Exception e)
                DisplayMessage("CLIENT >>> Error trying to Re-Connect...");
        public static void DisplayMessage(final String IncomingSms)
            System.out.println(IncomingSms);
        System.out.printf("Isms: %s", IncomingSms);  ///naah.
        public static String[][] getResponse()
            return Response;
        public static String getResponse(int row, int col)
            return Response[row][col];
    how can i do below using above code
    The program must be able to work in a non-networked mode. In this mode, the server and client must run in the same VM and must perform no networking, must not use loopback networking i.e: no “localhost” or “127.0.0.1”, and must not involve the serialization of any objects when communicating between the client and server components.
    The operating mode is selected using the single command line argument that is permitted.
    imust use a socket connection and define a protocol. networking must be entirely bypassed in the non-network mode.

  • FU Ant task failure: java.util.concurrent.ExecutionException: could not close client/server socket

    We sometimes see this failure intermitently when using the FlexUnit Ant task to run tests in a CI environment. The Ant task throws this exception:
    java.util.concurrent.ExecutionException: could not close client/server socket
    I have seen this for a while now, and still see it with the latest 4.1 RC versions.
    Here is the console output seen along with the above exception:
    FlexUnit player target: flash
    Validating task attributes ...
    Generating default values ...
    Using default working dir [C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\Source\Flex]
    Using the following settings for the test run:
    FLEX_HOME: [C:\dev\vert-d3flxcmn32\302100.41.0.20110323122739_d3flxcmn32]
    haltonfailure: [false]
    headless: [false]
    display: [99]
    localTrusted: [true]
    player: [flash]
    port: [1024]
    swf: [C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\build\commons.formatter.tests.unit.sw f]
    timeout: [1800000ms]
    toDir: [C:\DJTE\commons.formatter_swc\d3flxcmn32\reports\xml]
    Setting up server process ...
    Entry  [C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\build] already  available in local trust file at  [C:\Users\user\AppData\Roaming\Macromedia\Flash  Player\#Security\FlashPlayerTrust\flexUnit.cfg].
    Executing 'rundll32' with arguments:
    'url.dll,FileProtocolHandler'
    'C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\build\commons.formatter.tests.unit.swf '
    The ' characters around the executable and arguments are
    not part of the command.
    Starting server ...
    Opening server socket on port [1024].
    Waiting for client connection ...
    Client connected.
    Setting inbound buffer size to [262144] bytes.
    Receiving data ...
    Sending acknowledgement to player to start sending test data ...
    Stopping server ...
    End of test data reached, sending acknowledgement to player ...
    When the problem occurs, it is not always during the running of any particular test (that I am aware of). Recent runs where this failure was seen had the following number of tests executed (note: the total number that should be run is 45677): 18021, 18, 229.
    Here is a "good" run when the problem does not occur:
    Setting inbound buffer size to [262144] bytes.
    Receiving data ...
    Sending acknowledgement to player to start sending test data ...
    Stopping server ...
    End of test data reached, sending acknowledgement to player ...
    Closing client connection ...
    Closing server on port [1024] ...
    Analyzing reports ...
    Suite: com.formatters.help.TestGeographicSiteUrls
    Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 sec
    Suite: com.formatters.functionalUnitTest.testCases.TestNumericUDF
    Tests run: 13, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.071 sec
    Results :
    Tests run: 45,677, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 201.186 sec
    Has anyone else ran across this problem?
    Thanks,
    Trevor

    I am not sure if this information will help everyone, but here goes...
    For us, these problems with FlexUnit tests crashing the Flash Player appear to be related to couple of factors. Recently, we moved up from Flex 3.2 to Flex 4.1 as our development baseline.  Many people complained that their development environment (Flash Builder, etc.) was much more unstable.  Apparently, 4.1 produces SWFs that require more memory to run than 3.2 does?  Anyway, we still had Flash Player 10.1 as our runtime baseline.  Apparently, that version of the player was not as capable of running larger FlexUnit test SWFs, and would crash (as I posted months earlier).  I upgraded to the latest 10.3 standalone player versions, and the crashes have now ceased.  It would be nice to know exactly what was causing the crashes, but memory management (or lack of) is my best guess.
    So, if you are seeing these issues, try upgrading to the latest Flash Player version.
    Regards,
    Trevor

  • Client Server Socket With GUI

    Hi,
    As the name of the forum suggests I am very new to this whole thing.
    I am trying to write a client/server socket program that can encrypt and decrypt and has a GUI, can't use JCE or SSL or any built in encryption tools.
    I have the code for everything cept the encryption part.
    Any help, greatly appreciated,

    tnks a million but how do i incorporate that into the following client and server code:
    here's the client code:
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketClient extends JFrame
              implements ActionListener {
    JLabel text, clicked;
    JButton button;
    JPanel panel;
    JTextField textField;
    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    SocketClient(){ //Begin Constructor
    text = new JLabel("Text to send over socket:");
    textField = new JTextField(20);
    button = new JButton("Click Me");
    button.addActionListener(this);
    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.setBackground(Color.white);
    getContentPane().add(panel);
    panel.add("North", text);
    panel.add("Center", textField);
    panel.add("South", button);
    } //End Constructor
    public void actionPerformed(ActionEvent event){
    Object source = event.getSource();
    if(source == button){
    //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);
    public void listenSocket(){
    //Create socket connection
    try{
    socket = new Socket("HUGHESAN", 4444);
    out = new PrintWriter(socket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (UnknownHostException e) {
    System.out.println("Unknown host: HUGHESAN.eng");
    System.exit(1);
    } catch (IOException e) {
    System.out.println("No I/O");
    System.exit(1);
    public static void main(String[] args){
    SocketClient frame = new SocketClient();
         frame.setTitle("Client Program");
    WindowListener l = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.addWindowListener(l);
    frame.pack();
    frame.setVisible(true);
         frame.listenSocket();
    SERVER Code
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketServer extends JFrame
              implements ActionListener {
    JButton button;
    JLabel label = new JLabel("Text received over socket:");
    JPanel panel;
    JTextArea textArea = new JTextArea();
    ServerSocket server = null;
    Socket client = null;
    BufferedReader in = null;
    PrintWriter out = null;
    String line;
    SocketServer(){ //Begin Constructor
    button = new JButton("Click Me");
    button.addActionListener(this);
    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.setBackground(Color.white);
    getContentPane().add(panel);
    panel.add("North", label);
    panel.add("Center", textArea);
    panel.add("South", button);
    } //End Constructor
    public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    if(source == button){
    textArea.setText(line);
    public void listenSocket(){
    try{
    server = new ServerSocket(4444);
    } catch (IOException e) {
    System.out.println("Could not listen on port 4444");
    System.exit(-1);
    try{
    client = server.accept();
    } catch (IOException e) {
    System.out.println("Accept failed: 4444");
    System.exit(-1);
    try{
    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    out = new PrintWriter(client.getOutputStream(), true);
    } catch (IOException e) {
    System.out.println("Accept failed: 4444");
    System.exit(-1);
    while(true){
    try{
    line = in.readLine();
    //Send data back to client
    out.println(line);
    } catch (IOException e) {
    System.out.println("Read failed");
    System.exit(-1);
    protected void finalize(){
    //Clean up
    try{
    in.close();
    out.close();
    server.close();
    } catch (IOException e) {
    System.out.println("Could not close.");
    System.exit(-1);
    public static void main(String[] args){
    SocketServer frame = new SocketServer();
         frame.setTitle("Server Program");
    WindowListener l = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.addWindowListener(l);
    frame.pack();
    frame.setVisible(true);
         frame.listenSocket();
    Again help on this is very welcomed

  • Need help clarifying client/server TNS communication

    Im trying to get a clearer understanding of service/listener registration in the Oracle client/server architechure. Feel free to point out errors in my understanding.
    When an Oracle client connects to the server, it forms its connect descriptor based on the clients tnsnames.ora file. The client then checks the specified port on the host in the connect descriptor for a listener that is registered with the service defined in the
    (CONNECT_DATA =
    (SERVICE_NAME = TESTSERVICE)
    portion of the client's tnsnames file. Correct?
    Does the listener gets its list of SIDs its registered with from the SID_LIST section of the listener.ora file or the tnsnames file?
    If the listener gets its list of SIDs to register with from the tnsnames file, is that the tnsnames file on the server?
    If so, then what is the SID_LIST used for in the listener.ora file?
    Im trying to connect the dots and any help would be much appreciated.
    Thanks,

    Reading below documents would help you understand how client/server TNS communication works:-
    Listener Architecture
    http://download-east.oracle.com/docs/cd/B14117_01/network.101/b10775/architecture.htm#sthref445
    Configuring Naming Methods
    http://download-east.oracle.com/docs/cd/B14117_01/network.101/b10775/naming.htm
    Configuring and Administering the Listener
    http://download-east.oracle.com/docs/cd/B14117_01/network.101/b10775/listenercfg.htm

  • Problems Reading SSL  server socket  data stream using readByte()

    Hi I'm trying to read an SSL server socket stream using readByte(). I need to use readByte() because my program acts an LDAP proxy (receives LDAP messages from an LDAP client then passes them onto an actual LDAP server. It works fine with normal LDAP data streams but once an SSL data stream is introduced, readByte just hangs! Here is my code.....
    help!!! anyone?... anyone?
    1. SSL Socket is first read into  " InputStream input"
    public void     run()
              Authorization     auth = new Authorization();
              try     {
                   InputStream     input     =     client.getInputStream();
                   while     (true)
                   {     StandLdapCommand command;
                        try
                             command = new StandLdapCommand(input);
                             Authorization     t = command.get_auth();
                             if (t != null )
                                  auth = t;
                        catch( SocketException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection closed: " + e );
                             close( e );
                             break;
                        catch( EOFException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection close: " + e );
                             close( e );
                             break;
                        catch( Exception e )
                             //Way too many of these to trace them!
                             Message.Error( "Command not processed due to exception");
                             close( e );
                                            break;
                                            //continue;
                        processor.processBefore(auth,     command);
                                    try
                                      Thread.sleep(40); //yield to other threads
                                    catch(InterruptedException ie) {}
              catch     (Exception e)
                   close(e);
    2 Then data is sent to an intermediate function 
    from this statement in the function above:   command = new StandLdapCommand(input);
         public StandLdapCommand(InputStream     in)     throws IOException
              message     =     LDAPMessage.receive(in);
              analyze();
    Then finally, the read function where it hangs at  "int tag = (int)din.readByte(); "
    public static LDAPMessage receive(InputStream is) throws IOException
        *  LDAP Message Format =
        *      1.  LBER_SEQUENCE                           --  1 byte
        *      2.  Length                                  --  variable length     = 3 + 4 + 5 ....
        *      3.  ID                                      --  variable length
        *      4.  LDAP_REQ_msg                            --  1 byte
        *      5.  Message specific structure              --  variable length
        DataInputStream din = new DataInputStream(is);
        int tag = public static LDAPMessage receive(InputStream is) throws IOException
        *  LDAP Message Format =
        *      1.  LBER_SEQUENCE                           --  1 byte
        *      2.  Length                                  --  variable length     = 3 + 4 + 5 ....
        *      3.  ID                                      --  variable length
        *      4.  LDAP_REQ_msg                            --  1 byte
        *      5.  Message specific structure              --  variable length
        DataInputStream din = new DataInputStream(is);
           int tag = (int)din.readByte();      // sequence tag// sequence tag
        ...

    I suspect you are actually getting an Exception and not tracing the cause properly and then doing a sleep and then getting another Exception. Never ever catch an exception without tracing what it actually is somewhere.
    Also I don't know what the sleep is supposed to be for. You will block in readByte() until something comes in, and that should be enough yielding for anybody. The sleep is just literally a waste of time.

  • Publishing .fla project including client - server socket connection

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

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

  • BI Server Socket communication error

    All,
    OBIEE 10G with Oracle 11 database on Sun solaris.
    BI Server is randomly crashing with following error message:
    Odbc driver returned an error (SQLDriverConnectW).
    State: HY000. Code: 0. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 12008]
    Unable to connect to port 9703 on machine LOCALHOST. [nQSError: 12010]
    Communication error connecting to remote end point: address = LOCALHOST; port = 9703. [nQSError: 12002]
    Socket communication error at call=: (Number=-1) Unknown error (HY000)
    If you restart, it works fine for 1-2 days. Then again crash happens.
    Any ideas ..?
    ~R

    I've had similar issues due to insufficient memory on HP-UX. Probably best to raise a support log with oracle.

  • Best practice for client-server(Socket) application

    I want to build a client-server application
    1) On startup.. client creates connection to Server and keeps reading data from server
    2) Server keeps on sending different messages
    3) Based on messages(Async) from server client view has to be changed
    I tried different cases ended up facing IllegalStateChangeException while updating GUI
    So what is the best way to do this?
    Please give a working example .
    Thanks,
    Vijay
    Edited by: 844427 on Jan 12, 2012 12:15 AM
    Edited by: 844427 on Jan 12, 2012 12:16 AM

    Hi EJP,
    Thanks for the suggestion ,
    Here is sample code :
    public class Lobby implements LobbyModelsChangeListener{
        Stage stage;
        ListView<String> listView;
        ObservableList ol;
         public Lobby(Stage primaryStage) {
            stage = primaryStage;
               ProxyServer.startReadFromServer();//Connects to Socket Server
             ProxyServer.addLobbyModelChangeListener(this);//So that any data from server is fetched to Lobby
            init();
        private void init() {
              ProxyServer.getLobbyList();//Send
            ol = FXCollections.observableArrayList(
              "Loading Data..."
            ol.addListener(new ListChangeListener(){
                @Override
                public void onChanged(Change change) {
                    listView.setItems(ol);
         Group root = new Group();
        stage.setScene(new Scene(root));
         listView = new ListView<String>();
        listView.maxWidth(stage.getWidth());
         listView.setItems(ol);
         listView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        istView.setOnMouseClicked(new EventHandler<MouseEvent>(){
                @Override
                public void handle(MouseEvent t) {
    //                ListView lv = (ListView) t.getSource();
                    new NewPage(stage);
         root.getChildren().add(listView);
         @Override
        public void updateLobby(LobbyListModel[] changes) {
    //        listView.getItems().clear();
            String[] ar = new String[changes.length];
            for(int i=0;i<changes.length;i++)
                if(changes!=null)
    System.out.println(changes[i].getName());
    ar[i] = changes[i].getName();
    ol.addAll(ar);
    ProxyServer.javaProxyServer
    //Implements runnable
    public void run()
         ......//code to read data from server
    //make array of LobbyListModel[] ltm based on data from server
         fireLobbyModelChangeEvent(ltm);
    void addLobbyModelChangeListener(LobbyModelsChangeListener aThis) {
    this.lobbyModelsChangeListener = aThis;
         private void fireLobbyModelChangeEvent(LobbyListModel[] changes) {
    LobbyModelsChangeListener listner
    = (LobbyModelsChangeListener) lobbyModelsChangeListener;
    listner.updateLobby(changes);
    Exception :
    java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-5
             at line         ol.addAll(ar);
    But ListView is getting updated with new data...so not sure if its right way to proceed...
    Thanks,
    Vijay                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • 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?

  • Servlet Server Socket Communication problem

    Hi
    Iam having this problem ...when I read data in server line by line it works but when I try to read byte by byte server hangs. This is my code
    BufferedReader in = new BufferedReader(
    new InputStreamReader(
    clientSocket.getInputStream()));
    //it works fine when i do
    String strLine = in.readLine();
    //but hangs when I do like this
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int r = in.read();
    while(r != -1)
    baos.write(r);
    r = in.read();
    I am sending data from the client socket as
    out = new PrintWriter(addArtSocket.getOutputStream(), true);
    I just do out.println to send data.
    Is there something wrong that I am doing?
    Thanks
    vinitha

    hi,
    basically, I suggest that you have the communication
    channel in the same type between two ends. For example,
    if you decide to connect two side byt Stream, you just
    apply your code in the sort of Stream for I/O.
    If you decide to connect two sides by Reader/Writer, you
    apply your code in the sort of Reader/Writer for I/O.
    Don't mix them up. Although I don't know what may
    happen. For example, you want to pass an Object
    between two ends, you could use ObjectInputStream/
    ObjectOutputStream pair on two sides. Don't put
    ObjectInputStream in one side and talk to one sied
    which write data by other OutputStream filteer but
    not ObjectOutputStream .
    You may find something interesting.
    good luck,
    Alfred Wu

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

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

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

  • 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.

  • Large file transfer problems over client/server socket

    Hi,
    I wrote a simple chat problem in which I can send files from client to client. The problem is when I send large files over 101 MB the transfer freezes. I do not even get any error mesages in the console. The files I am sending are of any type (Ex mp3, movies, etc...). I am serializing the data into a "byteArray[packetSize]" and sending the file packet by packet until the whole file has been sent, and reconstructed on the other side. The process works perfectly for files smaller than 101MB, but for some reason freezes after that if the file is larger. I have read many forums and there aren't too many solutions out there. I made sure to use the .reset() method to reset my ObjectOutputStream each time I write to it.
    Here's my file sending code:
    byte[] byteArray = new byte[defaultPacketSize];
    numPacketsRequired = Math.ceil(fileSize / defaultPacketSize);
    try {
    int i = 0;
    reader = new FileInputStream(filePath);
    while (reader.available() > 0) {
    if (reader.available() < defaultPacketSize) {
    byte[] lastPacket = new byte[reader.available()];
    reader.read(lastPacket);
    try {
    if (socket == null || output == null) {
    throw new SocketException("socket does not exist");
    output.writeObject(lastPacket);
    output.reset();
    output.writeObject("DONE");
    output.reset();
    output.close();
    socket.close();
    catch (Exception e) {
    System.out.println("Exception ***: " + e);
    output.close();
    socket.close();
    else {
    reader.read(byteArray);
    try {
    if (socket == null || output == null) {
    throw new SocketException("socket does not exist");
    output.writeObject(byteArray);
    output.reset();
    catch (Exception e) {
    System.out.println("Exception ***: " + e);
    output.close();
    socket.close();
    reader.close();
    catch (Exception e) {
    System.out.println("COULD NOT READ PACKET");
    Here's my file receiving code:
    try {
    // The message from the client
    Object streamInput;
    FileOutputStream writer;
    byte[] packet;
    while (true) {
    streamInput = input.readObject();
    if (streamInput instanceof byte[]) {
    packet = (byte[]) streamInput;
    try {
    writer = new FileOutputStream(outputPath, true);
    writer.write(packet); //Storing the bytes on file
    writer.close();
    catch (Exception e) {
    System.out.println("Exception: " + e);
    else if (streamInput.equals("DONE")) {
    socket.close();
    input.close();
    break;
    catch (Exception e) {
    I'm looking for any way I can possibly send large files from client to client without having it freeze. Are there any better file transfer ways other than socket? I don't really want FTP. I think I want to keep it HTTP.
    Any suggestions would be helpful.Thanks!
    Evan

    I've taken a better look a the code you posted, and
    there is one problem with the receiving code. You
    keep repeatedly opening and closing the
    FileOutputStream. This is not going to be efficient
    as the file will keep needing to be positioned to its
    end.Yes sorry I did change that code so that it leaves the file open until completely done writing. Basically I have a progress bar that records how far along in the writing process the client is, and when the progress bar reaches 100%, meaning the file is complete, the file.close() method is invoked. Sorry about that.
    I also ran some memory tests using the "Runtime.getRuntime().totalMemory()", and "Runtime.getRuntime().freeMemory()" methods. I put these methods inside the loop where I read in the file and send it to the client. here's the output:
    Sender's free memory: 704672
    File reader read 51200 bytes of data.
    767548 left to read.
    Sender's runtime memory: 2818048
    Sender's free memory: 702968
    File reader read 51200 bytes of data.
    716348 left to read.
    Sender's runtime memory: 2818048
    Sender's free memory: 701264
    File reader read 51200 bytes of data.
    665148 left to read.
    Sender's runtime memory: 2818048
    Sender's free memory: 699560
    File reader read 51200 bytes of data.
    613948 left to read.
    Sender's runtime memory: 2818048
    Sender's free memory: 697856
    File reader read 51200 bytes of data.
    562748 left to read.
    Sender's runtime memory: 2818048
    Sender's free memory: 696152
    File reader read 51200 bytes of data.
    511548 left to read.
    Sender's runtime memory: 2818048
    Sender's free memory: 694448
    File reader read 51200 bytes of data.
    460348 left to read.
    Sender's runtime memory: 2818048
    Sender's free memory: 692744
    File reader read 51200 bytes of data.
    409148 left to read.
    Sender's runtime memory: 2818048
    Sender's free memory: 691040
    File reader read 51200 bytes of data.
    357948 left to read.
    Sender's runtime memory: 2818048
    Sender's free memory: 689336
    File reader read 51200 bytes of data.
    306748 left to read.
    Sender's runtime memory: 2818048
    Sender's free memory: 687632
    File reader read 51200 bytes of data.
    255548 left to read.
    Sender's runtime memory: 2818048
    Sender's free memory: 685928
    File reader read 51200 bytes of data.
    204348 left to read.
    Sender's runtime memory: 2818048
    Sender's free memory: 684224
    File reader read 51200 bytes of data.
    153148 left to read.
    Sender's runtime memory: 2818048
    Sender's free memory: 682520
    File reader read 51200 bytes of data.
    101948 left to read.
    Sender's runtime memory: 2818048
    Sender's free memory: 680816
    File reader read 51200 bytes of data.
    50748 left to read.
    Sender's runtime memory: 2818048
    Sender's free memory: 679112
    File reader read 50748 bytes of data.
    0 left to read.
    Creating last packet of size: 50748
    Last packet size after setting it equal to byteArray: 50748
    Here's the memory stats from the receiver:
    Receiver's free memory: 639856
    Receiver's total memory: 2842624
    Receiver's free memory: 638920
    Receiver's total memory: 2842624
    Receiver's free memory: 637984
    Receiver's total memory: 2842624
    Receiver's free memory: 637048
    Receiver's total memory: 2842624
    Receiver's free memory: 636112
    Receiver's total memory: 2842624
    Receiver's free memory: 635176
    Receiver's total memory: 2842624
    Receiver's free memory: 634240
    Receiver's total memory: 2842624
    Receiver's free memory: 633304
    Receiver's total memory: 2842624
    Receiver's free memory: 632368
    Receiver's total memory: 2842624
    Receiver's free memory: 631432
    Receiver's total memory: 2842624
    Receiver's free memory: 630496
    Receiver's total memory: 2842624
    Receiver's free memory: 629560
    Receiver's total memory: 2842624
    Receiver's free memory: 628624
    Receiver's total memory: 2842624
    Receiver's free memory: 627688
    Receiver's total memory: 2842624
    Receiver's free memory: 626752
    Receiver's total memory: 2842624
    Receiver's free memory: 625816
    Receiver's total memory: 2842624
    Receiver's free memory: 624880
    Receiver's total memory: 2842624
    Receiver's free memory: 623944
    Receiver's total memory: 2842624
    Receiver's free memory: 623008
    Receiver's total memory: 2842624
    Receiver's free memory: 622072
    Receiver's total memory: 2842624
    Receiver's free memory: 621136
    Receiver's total memory: 2842624
    Receiver's free memory: 620200
    Receiver's total memory: 2842624
    Receiver's free memory: 619264
    Receiver's total memory: 2842624
    Receiver's free memory: 618328
    Receiver's total memory: 2842624
    Receiver's free memory: 617392
    Receiver's total memory: 2842624
    Receiver's free memory: 616456
    Receiver's total memory: 2842624
    Receiver's free memory: 615520
    Receiver's total memory: 2842624
    Receiver's free memory: 614584
    this is just a sample of both receiver and sender's stats. Everything appears to be fine! Hope this message post isn't too long.
    Thanks!

  • Debug server socket already in use. Debug session will now terminate.

    sorry, double post. Delete this thread please.

    ServerSocket.setReuseAddress(true) does not work on vista. Why? The following code is OK on XP, but throw the above exception on vista.
         @Test
         public void test() throws Throwable {
              Thread t = new Thread() {
                   public void run() {
                        ServerSocket ss;
                        try {
                             ss = new ServerSocket( 11111 );
                             System.out.println( "In Thread: " + ss );
                             System.out.println( "In Thread: " + ss.accept() );
                        } catch (IOException e) {
                             e.printStackTrace();
              t.start();
              Socket cs = new Socket( (String)null, 11111 );
              System.out.println( cs );
              ServerSocket s = new ServerSocket();
              s.setReuseAddress( true );
              s.bind( new InetSocketAddress( cs.getLocalPort() ) );
              System.out.println( s );
         }

Maybe you are looking for