Stream vs Write (Client-Server)

Hi,
Ok, heres the problem, if someone can help me out it would be great! I am new to networking , and new to Java as well. I am trying to learn networking in Java by creating a simple Client-Server program.
Heres my Server :
import java.net.*;
import java.io.*;
public class MyServer {
     public static final int port = 8888;
     public static void main(String[] args) {
          ServerSocket serverSocket = null;
          Socket clientSocket = null;
          PrintStream os;
          try {
               serverSocket = new ServerSocket(port);
               System.out.println("Server initialized");
               System.out.println("Waiting for connection");
               clientSocket = serverSocket.accept();
               if(clientSocket.isConnected()) {
                    os = new PrintStream(clientSocket.getOutputStream());
                    os.print("Server: Connection established!");
          } catch (IOException e) {
               System.out.println(e);
               System.exit(1);
}Here's my Client:
import java.io.DataInputStream;
import java.io.PrintStream;
import java.net.*;
import java.io.*;
public class MyClient {
     public static final int port = 8888;
     public static void main(String args[]) {
          Socket clientSocket = null;
          DataInputStream is;
          try {
               clientSocket = new Socket("localhost", port);
               System.out.println("ClientSocket Initialized!");
               if (clientSocket.isConnected()) {
                    is = new DataInputStream(clientSocket.getInputStream());
                    String response;
                    while ((respon... [Show more]

thx for the reply jverd. I managed to get my Client Server working. Its basically like a chat now, client - server send messages back and forth, however, after they connect, only client can send messages, then after a little while only server can send messages, and this keeps looping. Any idea why? Heres my source:
Server:
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class Server {
     public static final int port = 8888;
     public static void main(String[] args) {
          ServerSocket sSoc;
          Socket soc;
          PrintStream os;
          DataInputStream in;
          Scanner scanner;
          try {
               sSoc = new ServerSocket(port);
               soc = sSoc.accept();
               os = new PrintStream(soc.getOutputStream(), true);
               in = new DataInputStream(soc.getInputStream());
               System.out.println("Connection established! Initializing server");
               scanner = new Scanner(System.in);
               while(true) {
                    String outgoing, incoming;
                    outgoing = scanner.nextLine();
                    os.println(outgoing);
                    if(outgoing.equals("exit")) break;
                    if((incoming = in.readLine())!=null) {
                         System.out.println(incoming);
                    if(incoming.equals("exit")) break;
               in.close();
               out.close();
               soc.close();
               sSoc.close();
          } catch (IOException e) {
               System.out.println(e);
}Client
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class Client {
     public static final int port = 8888;
     public static void main(String[] args) {
          Socket soc;
          PrintStream os;
          DataInputStream in;
          Scanner scanner;
          try {
               soc = new Socket("localhost", port);
               os = new PrintStream(soc.getOutputStream(), true);
               in = new DataInputStream(soc.getInputStream());
               System.out.println("Connection established! Initializing Client");
               scanner = new Scanner(System.in);
               while(true) {
                    String incoming, outgoing;
                    outgoing = scanner.nextLine();
                    os.println(outgoing);
                    if(outgoing.equals("exit")) break;
                    if((incoming = in.readLine())!=null) {
                         System.out.println(incoming);
                    if(incoming.equals("exit")) break;
               in.close();
               out.close();
               soc.close();
               sSoc.close();
          } catch (IOException e) {
               System.out.println(e);
}Edited by: b-2_spirit on Sep 21, 2010 10:41 PM
Edited by: b-2_spirit on Sep 21, 2010 10:42 PM

Similar Messages

  • Client server programming

    Hi;
    I want to learn client server programming on using windows xp for the client and windows server 2003.
    I downloaded the 9.2 windows xp database version for the client . What do I need to download for the server? I see that there is a 32 and 64 bit version for the server.
    Thanks for your help!

    What I was asking is what should I install on the server
    the 32 or 64 bit version of oracle?
    I want to learn how to write client/server programs using Oracle.
    I have a network at home with one computer serving as the client and another has server 2003 on it.
    Again Thanks for your help!

  • File transfer, read write through sockets in client server programming java

    Hello All, need help again.
    I am trying to create a Client server program, where, the Client first sends a file to Server, on accepting the file, the server generates another file(probably xml), send it to the client as a response, the client read the response xml, parse it and display some data. now I am successful sending the file to the server, but could not figure out how the server can create and send a xml file and send it to the client as response, please help. below are my codes for client and server
    Client side
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class XMLSocketC
         public static void main(String[] args) throws IOException
              //Establish a connection to socket
              Socket toServer = null;
              String host = "127.0.0.1";     
              int port = 4444;
              try
                   toServer = new Socket(host, port);
                   } catch (UnknownHostException e) {
                System.err.println("Don't know about host: localhost.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to host.");
                System.exit(1);
              //Send file over Socket
            //===========================================================
            BufferedInputStream fileIn = null;
              BufferedOutputStream out = null;
              // File to be send over the socket.
              File file = new File("c:/xampp/htdocs/thesis/sensorList.php");
              // Checking for the file to be sent.
              if (!file.exists())
                   System.out.println("File doesn't exist");
                   System.exit(0);
              try
                   // InputStream to read the file
                   fileIn = new BufferedInputStream(new FileInputStream(file));
              }catch(IOException eee)
                   System.out.println("Problem, kunne ikke lage fil");
              try
                   InetAddress adressen = InetAddress.getByName(host);
                   try
                        System.out.println("Establishing Socket Connection");
                        // Opening Socket
                        Socket s = new Socket(adressen, port);
                        System.out.println("Socket is clear and available.....");
                        // OutputStream to socket
                        out = new BufferedOutputStream(s.getOutputStream());
                        byte[] buffer = new byte[1024];
                        int numRead;
                        //Checking if bytes available to read to the buffer.
                        while( (numRead = fileIn.read(buffer)) >= 0)
                             // Writes bytes to Output Stream from 0 to total number of bytes
                             out.write(buffer, 0, numRead);
                        // Flush - send file
                        out.flush();
                        // close OutputStream
                        out.close();
                        // close InputStrean
                        fileIn.close();
                   }catch (IOException e)
              }catch(UnknownHostException e)
                   System.err.println(e);
            //===========================================================
            //Retrieve data from Socket.
              //BufferedReader in = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
              DataInputStream in = new DataInputStream(new BufferedInputStream(toServer.getInputStream()));
              //String fromServer;
            //Read from the server and prints.
              //Receive text from server
              FileWriter fr = null;
              String frn = "xxx_response.xml";
              try {
                   fr = new FileWriter(frn);
              } catch (IOException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              try{
                   String line = in.readUTF();                    //.readLine();
                   System.out.println("Text received :" + line);
                   fr.write(line);
              } catch (IOException e){
                   System.out.println("Read failed");
                   System.exit(1);
            in.close();
            toServer.close();
    public class XMLSocketS
          public static void main(String[] args) throws IOException
              //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4444);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
              while (true)
                        try
                             clientLink = serverSocket.accept();
                           System.out.println("Server accepts");
                             BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             // close the link to client
                             clientLink.close();                         
                             // close InputStream
                             inn.close();                         
                             // flush
                             ut.flush();                         
                             // close OutputStream
                             ut.close();     
                             //Sending response to client     
                             //============================================================
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
    }

    SERVER
    import java.net.*;
    import java.io.*;
    public class XMLSocketS
          public static void main(String[] args) throws IOException
                   //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4545);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
                  try
                             clientLink = serverSocket.accept();
                         System.out.println("Server accepts the client request.....");
                         BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             ut.flush();                         
                             //Sending response to client     
                             //============================================================
                             BufferedInputStream ftoC = null;
                             BufferedOutputStream outtoC = null;
                             // File to be send over the socket.
                             File file = new File("c:/xampp/htdocs/thesis/user_registration_response.xml");
                             try
                                  // InputStream to read the file
                                   ftoC = new BufferedInputStream(new FileInputStream(file));
                             }catch(IOException eee)
                             {System.out.println("Problem reading file");}
                             // OutputStream to socket
                             outtoC = new BufferedOutputStream(clientLink.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int noRead;
                             //Checking if bytes available to read to the buffer.
                             while( (noRead = ftoC.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  outtoC.write(buffer, 0, noRead);
                             outtoC.flush();
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
          }CLIENT SIDE
    import java.io.*;
    import java.net.*;
    public class XMLSocketC
              @SuppressWarnings("deprecation")
              public static void main(String[] args)
                   // Server: "localhost" here. And port to connect is 4545.
                   String host = "127.0.0.1";          
                   int port = 4545;
                   BufferedInputStream fileIn = null;
                   BufferedOutputStream out = null;
                   // File to be send over the socket.
                   File file = new File("c:/xampp/htdocs/thesis/sensorList.xml");
                   try
                        // InputStream to read the file
                        fileIn = new BufferedInputStream(new FileInputStream(file));
                   }catch(IOException eee)
                   {System.out.println("Problem");}
                   try
                             System.out.println("Establishing Socket Connection");
                             // Opening Socket
                             Socket clientSocket = new Socket(host, port);
                             System.out.println("Socket is clear and available.....");
                             // OutputStream to socket
                             out = new BufferedOutputStream(clientSocket.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int numRead;
                             //Checking if bytes available to read to the buffer.
                             while( (numRead = fileIn.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  out.write(buffer, 0, numRead);
                             // Flush - send file
                             out.flush();
                             //=======================================
                             DataInputStream in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
                             BufferedWriter outf = new BufferedWriter(new FileWriter("c:/xampp/htdocs/received_from_server.txt",true));
                             String str;
                             while(!(str = in.readLine()).equals("EOF")) {     
                                  System.out.println("client : Read line -> <" + str + ">");
                                  outf.write(str);//Write out a string to the file
                                  outf.newLine();//write a new line to the file (for better format)
                                  outf.flush();
                             //=======================================
                             // close OutputStream
                             out.close();
                             // close InputStrean
                             fileIn.close();
                             // close Socket
                             clientSocket.close();
                        }catch (IOException e)
                        {System.out.println("Exception.");}
         Could you please point where am I doing the stupid mistake, client to server is working properly, but the opposite direction is not.
    Thanks

  • JMF - client server video streaming how to stop

    Hi
    I am able to stream video from a server to multiple clients using AVReceive2 and AVTransmit2 from the JMF site.
    Iam developing a client server project. I have modified the above code such that Iam able to start and stream the videos by calling on servlets and socket connections.
    The AVTransmit2 code does not however have a stop button and it uses a thread.sleep method. I do not know how to add a stop button in the GUI on AVReceive2 to call on AVTransmit2.
    I am using sockets to communicate to and from the server. Do i have to use RMI or is there another easier way to call stop from the client which would stop the transmission on the server?
    Also, after the video file has been successfully streamed, when I refresh and try to connect again, the server is invoked and __it starts transmission_,_ but the servlet which calls the AVReceive fails and the frame does not show. Any possible reasons why?
    Thanks in advance.
    Junior

    I don't know the speed of the connection.
    4-10 users usually.
    .11b or .11g I don't know.
    microwave nearby - I don't know
    5-6 other wifis - yes
    I will try Safari, thanks!
    Thanks for the update. The speed of the Wi-Fi in the
    coffee shop will depend on many factors. What is the
    speed of their connection to the Internet? How many
    people are sharing the Wi-Fi? Is it 802.11b or
    802.11g? Do they have a microwave operating nearby?
    That will often interfere. Are there additional Wi-Fi
    networks nearby? That can interfere as well. It's
    possible that it was their network that's causing
    your trouble. But, to rule that out, did you try
    using Safari instead? You might make sure you have an
    up-to-date version of the Flash player which you can
    get at http://www.adobe.com
    I have Clearwire
    at home, it's basically like wireless DSL. It's not
    as fast as cable Internet access, but it is portable.
    I only mentioned it because it would indicate that
    you don't need cable speed to watch the videos
    without buffering.
    -Doug

  • Writng-Reading stream through client-server application

    I am developing a client-server application which is the client sends a sentence to the server and the server will convert the sentence from small letters to all capital letters. The problem is when the sentence send by the client contains special character such as Registered Trade Mark or Copyright , the server receive the sentence but the special character has changed to undefined symbol. After the server do the conversion process, the server couldn't send back the sentence because of the undefined symbol. It will make the system hangs.
    I use socket connection to do the process. The system use DataOutputStream object to pass the sentence . The source code is as below:
    Socket clientSocket = new Socket("localhost", 111);
    DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    sentence = "Stomach-Comfort is the all-natural alternative to over-the-counter products, such as Tums�, Rolaids� and Pepcid AC�.";
    outToServer.writeUTF(sentence + '\n');
    modifiedSentence = inFromServer.readLine();
    System.out.println("FROM SERVER: " + modifiedSentence);
    Any body can help me?

    Well, I think that this would work but I haven't tried it, but you could evaluate the numerical value of each
    character and see if it falls within the range of ASCII fields that you want to convert.
    If not don't convert it.
    So for example,
    for each char in your stream:
    1) get a char's numerical value
    2) If between 97-122 decimal
    convert to the capital (forgot the exact method name)
    3) else
    keep value as it is.

  • Stream of data from server to client, what is a good form

    I am building a small client server app where the server is constantly sending data to the client. The data is such that it readily lends itself to being in key/value pairs. My thought is to basically have the server send out a string of text to the client like "1:name, 2:age, 3:date, 4:salary" and then have the client parse it out. I can have an object, and just make a toString() method that spits out the fields in that way. But...
    Do you guys think this is a good way of sending data out. I will only have at most 20 clients running at once, and the data will get no more than say, 50 key/value pairs. Another way I suppose is to convert it to XML, I'd have to read more about it because I'm not exactly sure how to encapsulate data into XML format or how to use Java's DOM API, but perhaps that is overkill, what do you guys think. Also is there an existing Java parsing API out there already, somethign that I haven't found, that would make all of this very easy? As of right now I have to make sure my output stream is in good form, and then still the client will have to do some kludging parsing with commas and what not. Any suggestions would be appreciated.

    Today you only want a few key/value pairs but tomorrow you will decide you need a more complex data structure. I would probably use Serialization using ObjectInput/OutputStream or, as you have considered, XML.
    If both sides are to be written in Java then I would probably use Serialization.

  • Use two streams to manager client video/audio,Can i combine streams and record it with server AS API

    Use two streams to manager client video/audio,Can i combine streams and record it with server AS API
    I tried Stream.play()
    var s=Stream.get("combine");
    s.play("video");
    s.play("audio",null,null,false);
    s.record("append");
    it's don't work!!

    Thanks, that's what I had thought. Our domain.com zone is sourced internally and replicated to our advertisers for external users, so there's no way to change the result for internal vs external users.
    This is a rudimentary question that I should already know but I sort of inherited this after it was built: Can I have users sign in with their email address ([email protected]) but under the hood, their SIP address is [email protected]? This would let users
    sign in with an address they expect, but it would take advantage of the the local lyncdiscoverinternal record.
    Thanks,
    Matt

  • App-V 5 Full Infrastructure Apps take long time to stream to the client

    Hi was wondering if anyone has the same issue as i am or knows a fix for this, below is my problem and the troubleshooting i have done.
    Overview of problem
    App-V 5 apps delivered via App-V 5 full infrastructure take a long time to stream to the client and this means the user has to wait if they try and run an application before it has streamed to the client. Users sometimes have to
    wait 2 or 3 minutes for an application to stream and this is about 40 times slower than basic SMB and HTTP transfer tests show the system is capable of (see performance results below).
    App-V 4.6 apps delivered via App-V 4.6 full infrastructure and HTTP streaming are fine.
    Overview of environment
    App-V 5.0 SP1 Full Infrastructure.
    App-V servers are running Server 2012 on Hyper-V 3 or ESX 5.1 with 2 x vCPU and 4GB RAM.
    SQL servers are a SQL 2012 cluster.
    Separate servers for SQL, management, publishing, content and reporting.
    Management, Publishing and Content servers have two servers per role and NLB to provide load balancing. So 7 servers (2 x Man, 2 x Pub, 2 x Content, 1 x Reporting)
    Two further sites with 2 x Pub and 2 x Content each. All publishing servers pointed at the load balance address for management.
    Content delivered via HTTP
    Clients are physical desktops and laptops running Windows 7 SP1 x86 and Windows 8 x86
    App-V client is 5.0SP1
    Clients are pointed at their nearest publishing server NLB via a script which looks up the client IP address and uses PowerShell to configure the publishing server
    Content is streamed from the nearest content server NLB by setting the PackageSourceRoot to the nearest content NLB (via the same PowerShell script above).
    App-V apps delivered per-user via AD group. One AD group per application. Approximately 200 App-V apps published so far - will eventually reach 400 as we sequence more. About 9000 users.
    Analysis performed so far
    Servers not heavily loaded. CPU averages 5%. Lots of RAM free. Very low disk IO. Problem also occurs out-of-hours so we are 99.9% certain that server resources are not a cause.
    Streaming performance is the same from all 6 content servers and all 3 NLB addresses (tested by changing the value of PackageSourceRoot). Wireshark used to confirm packages are really streaming from the correct location, enforcing
    our belief that the problem isn't at the server end (unless all 6 servers are affected).
    Streaming via both HTTP and SMB2.1 is approximately the same (tested by changing the value of PackageSourceRoot between http://xxxx and \\server\AppVContent).
    Wireshark used to confirm we really are using the protocol we think we are using.
    All clients exhibit the same behaviour. Issue reported by many users. 5 test PCs chosen at random at all 3 sites confirmed to have the slow streaming problem.
    Slow streaming from both Hyper-V and VMware ESX servers.
    Client not heavily loaded.
    Affects all App-V apps although it obviously affects the larger ones more.
    All App-V apps have a Feature Block 1 setup.
    If we copy the ".appv" file from the server to the client via either HTTP or SMB then it's reasonably quick (up to 480Mb/s). So we don't believe the network or servers are at fault. For example:
    We can copy a 149MB .appv file via SMB from the content server to the client in 5 seconds.
    We copy HTTP download the .appv file from the content server using IE on the client in 5 seconds.
    But if you ask the App-V 5 client to fully download the sequence then it takes 2 - 3 minutes.
    The App-V 4.6 client takes about 8 - 10 seconds to fully download a similar sized application.
    App-V 5 publishing works fine - when a new user logs on they get their list of application straight away, it's just the streaming which is slow.
    Once the App-V app has streamed locally it runs fine and with a decent performance.
    Looking at a Wireshark trace of the streaming you can see that the slow performance is due to the transfer stopping and starting a lot. You only notice this when you zoom into the performance graph a fair bit.
    Each time the HTTP server stops sending traffic, it doesn't start again until the client sends a "TCP Window update". Each "stop" is of a different length, but just taking a few from the middle I get 0.06s, 0.11s,
    0.13s wasted etc.
    I can see that it's the client stopping the transfer by reducing its advertised TCP Window Size. I'll provide an example:
    Server sends 9 x 1514 bytes. Client responds with an ACK and a Window size of 54016 bytes (256x211)
    Server sends 11 x 1514 bytes. Client responds with an ACK and a Window size of 37888 bytes (256x148)
    Server sends 10 x 1514 bytes. Client responds with an ACK and a Window size of 23296 bytes (256x91)
    Server sends 15 x 1514 bytes. Client responds with an ACK and a Window size of 1280 bytes (5 x 256)
    Server stops sending (I'm guessing because the client advertised Window size was less than a single packet's worth of bytes)
    <0.1 seconds passes>
    Client sends a "TCP Window Update" re-advertising a TCP window size of 65536 (256x256).
    Server starts transmitting again
    So the way I see this is that the App-V 5 client is controlling the transfer speed by utilising TCP Window flow control. The trace was taken at the client end so there's no room for anything on the network to be fiddling with flow
    control (and we've confirmed there are no traffic shapers in the loop).
    We've also tried streaming directly from the local client by copying some App-V 5 apps down to the client, creating a SMB share on the client and changing PackageSourceRoot to \\localhost\AppVContent (i.e. so we are streaming directly
    from the client to the client - to remove the network from the equation) and there is only an improvement of 5 to 10 seconds. So we know it's nothing to do with the network or the servers.
    We've tried turning off TCP auto-tuning on the client with:
    netsh interface tcp set global autotuninglevel=disabled
    and turning off TCP chimney offloading (which is off anyway because the NIC doesn't support it and Netstat -t output shows "InHost" for offload state for all connections) with:
    netsh int tcp set global chimney=disabled
    and nothing has improved.
    So we've now focussed on the extraction of the .appv (ZIP) file on the client.
    Using Windows Explorer it takes 75 seconds to extract the ZIP file
    Using 7ZIP it takes 9 seconds to extract the ZIP file
    Yeah we've always known that the Explorer ZIP engine is terrible. That's why we use 7ZIP or WinRAR on our clients.
    So we've started to wonder if the problem with the slow App-V 5 streaming is because the client is downloading the .appv file and extracting it as it goes along in a single thread. If the App-V 5 client is using the same terrible
    ZIP engine that Explorer does then that would explain the slow performance. The "download" appears to take a long time because the client is using TCP flow control to slow the transfer since it's extracting the .appv file using a very slow ZIP engine
    and it's all in a single thread.

    Guys,
    Just wanted to give you a brief update basically close this thread as Answered.
    We had submitted 4 App-V 5 Bugs to Microsoft and these were reproducible and an explanation was given on work around to them. Microsoft
    sent down a App-v developer to have a look at our problems. They said they will try and include the Bug fixes in SP2 which should be out in a few weeks or they will definitely be included in SP3.
    In regards to the slow streaming it all came down to the Disk IO.
    We found that you could simply enable "Turn off
    Windows write-cache buffer flushing on the device", then start streaming the app and then disable "Turn
    off Windows write-cache buffer flushing on the device" immediately after
    (we don't want to leave it on) and that basically fixed the issue.
    But a normal user would not have permissions to do
    this, so a code was written to enable and disable this option.
    Apology for not going in detail, like my opening thread, its very late. 
    but if you would like a detailed analysis please message me.
    I would like to Thank the Talented Consultant who designed and implemented are App-V infrastructure who found the bugs and created all
    the work around and who also emailed the detailed analysis of the problems to Microsoft that got them interested.
    Simon Bond from Ultima Business Solutions.
    Thank you

  • Thread problem in JavaNIO client server application

    **Dear experts,**
    I have problem with server which is nonblocking nio server, after registering one client the server is not registering other clients can some body told me, what is going on why sever is not showing any activity*
    this is Tour proxy class which is at client site and dealing with server and updating GUI on client site:*
    public void run() {
              connect(host);
              running = true;
              while (running) {
                   readIncomingMessages();
                   // nap for a bit
                   try {
                        Thread.sleep(50);
                   catch (InterruptedException ie) {
         } this is GUI which is dealing with Tourproxy
    class WrapNetTour3D
    void createSceneGraph(String userName, String tourFnm,
                                                 double xPosn, double zPosn)
      // initialize the scene
        sceneBG = new BranchGroup();
        bounds = new BoundingSphere(new Point3d(0,0,0), BOUNDSIZE);
        // to allow clients to be added/removed from the world at run time
        sceneBG.setCapability(Group.ALLOW_CHILDREN_READ);
        sceneBG.setCapability(Group.ALLOW_CHILDREN_WRITE);
        sceneBG.setCapability(Group.ALLOW_CHILDREN_EXTEND);
        lightScene();         // add the lights
        addBackground();      // add the sky
        sceneBG.addChild( new CheckerFloor().getBG() );  // add the floor
        makeScenery(tourFnm);      // add scenery and obstacles
        TP = new TourProxy("localhost",this,obs);
        makeContact();     // contact server (after Obstacles object created)
        addTourist(userName, xPosn, zPosn);     
                                // add the user-controlled 3D sprite
        sceneBG.compile();   // fix the scene
      } // end of createSceneGraph()
    private void makeContact()
      /* Contact the server, and set up a TourProxy to monitor the
         server. */
        try {
               TP.start();
        catch(Exception e)
        { System.out.println("No contact with server");
          System.exit(0);
      }  // end of makeContact()
    ....} this is class which is initializing the above class WrapNetTour3D:
      public NetTour3D(String args[])
        super("3D NetTour");
        processArgs(args);
        setTitle( getTitle() + " for " + userName);
        Container c = getContentPane();
        c.setLayout( new BorderLayout() );
        w3d = new WrapNetTour3D(userName, tourFnm, xPosn, zPosn);
        c.add(w3d, BorderLayout.CENTER);
         addWindowListener( new WindowAdapter() {
           public void windowClosing(WindowEvent e)
           { w3d.closeLink(); }
        pack();
        setResizable(false);    // fixed size display
        setVisible(true);
      } // end of NetTour3D() and this is server:
    public NIOTourServer( String string, int port) throws IOException {
              this.addr = string;
              this.port = port;
              writeBuffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
              dataMap = new HashMap<SocketChannel, List<byte[]>>();
              clients = new LinkedList();
              userName = "?";
              startServer();
         private void startServer() throws IOException {
              // create selector and channel
              this.selector = Selector.open();
              ServerSocketChannel serverChannel = ServerSocketChannel.open();
              serverChannel.configureBlocking(false);
              // bind to port
              InetSocketAddress listenAddr = new InetSocketAddress(this.addr,
                        this.port);
              serverChannel.socket().bind(listenAddr);
              serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
              log("Echo server ready. Ctrl-C to stop.");
              // processing
              while (true) {
                   // wait for events
                   this.selector.select();
                   // wakeup to work on selected keys
                   Iterator keys = this.selector.selectedKeys().iterator();
                   while (keys.hasNext()) {
                        SelectionKey key = (SelectionKey) keys.next();
                        // this is necessary to prevent the same key from coming up
                        // again the next time around.
                        keys.remove();
                        if (!key.isValid()) {
                             continue;
                        if (key.isAcceptable()) {
                             this.accept(key);
                        } else if (key.isReadable()) {
                             this.read(key);
                        } else if (key.isWritable()) {
                             //this.write(key);
         private void accept(SelectionKey key) throws IOException {
              ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
              SocketChannel channel = serverChannel.accept();
              clients.add(channel);
              log.info("got connection from: " + channel.socket().getInetAddress());
              channel.configureBlocking(false);
              // write welcome message
              channel.write(ByteBuffer.wrap("Welcome, this is the Tour server\r\n"
                        .getBytes("US-ASCII")));
              Socket socket = channel.socket();
              SocketAddress remoteAddr = socket.getRemoteSocketAddress();
              log.info("Connected to: " + remoteAddr);
              // register channel with selector for further IO
              dataMap.put(channel, new ArrayList<byte[]>());
              channel.register(this.selector, SelectionKey.OP_READ);
         private void sendMessage(SocketChannel channel, String mesg) {
              prepWriteBuffer(mesg);
              channelWrite(channel, writeBuffer);
         private void read(SelectionKey key) throws IOException {
              try {
                   SocketChannel channel = (SocketChannel) key.channel();
                   ByteBuffer buffer = ByteBuffer.allocate(4192);
                   int numRead = -1;
                   // read from the channel into our buffer
                   numRead = channel.read(buffer);
                   // check for end-of-stream
                   if (numRead == -1) {
                        log.info("disconnect: " + channel.socket().getInetAddress()
                                  + ", end-of-stream");
                        channel.close();
                        clients.remove(channel);
                        sendBroadcastMessage("logout: "
                                  + channel.socket().getInetAddress(), channel);
                   } else {
                        byte[] data = new byte[numRead];
                        System.arraycopy(buffer.array(), 0, data, 0, numRead);
                        String dataReturn = new String(data, "US-ASCII");
                        log("Got: " + dataReturn);
                        processClient(dataReturn,channel);
              } catch (IOException ioe) {
                   log.warn("error during select(): ", ioe);
              } catch (Exception e) {
                   log.error("exception in run()", e);
         private void processClient(String line,SocketChannel from)
         /* Stop when the input stream closes (is null) or "bye" is sent
               Otherwise pass the input to doRequest(). */
              //String line;
              boolean done = false;
              while (!done) {
                   // if((line = in.readLine()) == null)
                   if(line == null)
                        done = true;
                   else {
                        // System.out.println(userName + " received msg: " + line);
                        if (line.trim().equals("bye"))
                             done = true;
                        else
                             doRequest(line.trim(), from);
         }  // end of processClient()
    ...} i thought there is some problem with threads
    can somebody tell me how can i deal with it, as i m new newbie and how could i avoid problems in such design and complex application so that i am able to complete this application
    please help,
    thanks a lot
    jibbylala
    Edited by: 805185 on Nov 23, 2010 10:43 AM
    Edited by: 805185 on Nov 23, 2010 11:36 AM

    ejp:Here you are assuming that the socket is readable. Check it. You also need to check for isConnectable(), and if true, try finishConnect(), and if that succeeds deregister OP_CONNECT and register OP_READ.
    where i do this or it should be  done in connect method() or in readIncomingMessages() .
    the current problem is connecting 2nd client.
    i thought the other steps came later
    i changed the connect method like this :
    private void connect(String hostname) {
              try {
                   InetAddress addr = InetAddress.getByName(hostname);
                   int mnInterestOps = 0;
                   try
                        channel = SocketChannel.open();
                        channel.configureBlocking(false);
                        InetSocketAddress mxRemoteAddress = new InetSocketAddress(addr, PORT);
                        boolean t_connect = channel.connect(mxRemoteAddress);
                        if (t_connect)
                             System.out.println("connected");
                             mnInterestOps = SelectionKey.OP_WRITE | SelectionKey.OP_READ ;
                        else
                             mnInterestOps = SelectionKey.OP_CONNECT;
                        //create the selector
                        readSelector= SelectorProviderImpl.provider().openSelector();
                        //register the channel with the selector indicating an interest
                        SelectionKey x_key = channel.register(readSelector, mnInterestOps);
                        //select loop
                        while(true)
                             //block until connect response is received
                             int selectReturn = readSelector.select(0);
                             if (selectReturn == 0)
                                  System.out.println("select returned 0");
                             Set myKeys = readSelector.selectedKeys();
                             if (!myKeys.isEmpty())
                                  Iterator x_readyKeysIterator = myKeys.iterator();
                                  // Iterate over the set of keys for which events are available
                                  while (x_readyKeysIterator.hasNext())
                                       SelectionKey x_selectionKey = (SelectionKey) x_readyKeysIterator.next();
                                       // Remove selected key
                                       x_readyKeysIterator.remove();
                                       if (x_selectionKey.isValid())
                                            if (x_selectionKey.isConnectable()) {
                                                 channel.finishConnect();
                                                 System.out.println("connection 2 accepted");
                                            else if (x_selectionKey.isWritable()) {
                                                 System.out.println("writable channel, select return =" + selectReturn);
                                                 x_selectionKey.cancel();
                                            else if (x_selectionKey.isReadable()) {
                                                 System.out.println("readable channel" + selectReturn);
                                       else
                                            //cancel the channel registration with this selector
                                            x_selectionKey.cancel();
                                            System.out.println("key not valid");
                        } //end while(true)
                   } //end try block
                   catch (Exception ex)
                        System.out.println("exception " + ex);
              catch (UnknownHostException uhe) {
                   uhe.printStackTrace();
              catch (Exception e) {e.printStackTrace();
         } but now i m getting NPE HERE in tourproxy class.
    this is method which is calling channelWrite() and this method sendMessage()  i m calling from different other gui classes and i don't think so that i need  to pass the channel from there:
    void sendMessage(String mesg) {
              prepWriteBuffer(mesg);
              channelWrite(channel, writeBuffer);
    private void channelWrite(SocketChannel channel, ByteBuffer writeBuffer) {
    nbytes += channel.write(writeBuffer); *//channel is null here*
    } *can you just  tell me why it is null as i m populating it in connect method or what should i do?
    PS: i already created chat application with javaNIO....
    The output of this application  is nothing but a sprite which has to move simultaneously on two clients but it is not because server can't register more than one client.

  • Client/Server API with push?

    I set up a simple Socket client server architecture with the Java socket API. However, my clients sometimes are initiators or requests, and sometimes my server is the initiator of infos. Example: client want to get infos from server but also want to tell the server something. The server tells all registered clients something but also can accept requests from clients. So both sides are client AND server (depending on what they currently want to do).
    The socket API is just a classic client/server API, i.e. a server listens and a client sends requets and get responses. For my server to send requests to all clients, this is not enough. Is the only way to have all clients offering a socket server on their computer, too? so that this 2-way-request-communication works?
    This is basically some kind of "push" technology, but i don't want my clients to "poll" the server just to emulate the feature of sending requests from the server to the client. Is there some other (perhaps non-socket) API that offers this?

    @sjasja: how is the socket api symmetrical?It is, trust me! Connection initiation isn't, but after that it is. (Let's assume connected TCP/IP.)
    The server does bind() and accept(), the client does connect(). After that, the connection is symmetrical: either end can issue any number of read() and write() calls in any order. You write() to a socket, it pops out from read() at the other end (though not necessarily as a single packet; TCP/IP is stream oriented, so write() "packets" can and will be glued together, or fragmented at the whimsy of network routers and friends.)
    - accept() //wait for client to send request
    - socket.getInputStream() //read request
    - socket .getOutputStream() //write responseThose don't read or write; they get streams which you can read from and write to.
    In the server, when accept() returns a new connection, you'd start a reader thread for that client. The thread would read() (or readLine() if you implement a line-oriented protocol) and handle the incoming messages. Whenever you want to write to the client, write to the stream returned by socket.getOutputStream(). You may need to synchronize writes if you have several threads that do sequences of write()s that need to arrive at the client sequentially.
    As to the difficulty of socket programming: I don't think it particularly difficult. But then I've written dozens of socket programs since my first one in '85... The Java Tutorial socket chapter shows a simple client/server pair; not terribly difficult I think. In particular, check out the KKMultiServer at the bottom of the sample server chapter.

  • TCP Client Server - how to set timeout and bandwidth option

    Hi Friends,
    I am writing a simple TCP based client-server app and I would like the connection to be dropped after a certain time of inactivity and also I would like to control the connection's bandwidth. I would appreciate if someone can throw some pointers as to how this can be done.
    I have tried this so far, for Timeout I am trying to do this:
    sock.setSoTimeout(10000);But I think this is not the right way as this will disconnect the server from all client connections I guess. I think the better way would be to write a timer or something for each connection but I don't know how...
    Any help?

    Micks80 wrote:
    Hi Friends,
    I am writing a simple TCP based client-server app and I would like the connection to be dropped after a certain time of inactivity and also I would like to control the connection's bandwidth. I would appreciate if someone can throw some pointers as to how this can be done.
    I have tried this so far, for Timeout I am trying to do this:
    sock.setSoTimeout(10000);But I think this is not the right way as this will disconnect the server from all client connections I guess.Wrong in a couple of ways.
    1) That doesn`t disconnect anything. It causes a read that reaches that time in blocking to be unblocked and an exception (java.net.SocketTimeoutException) is thrown. The Socket is still just fine and can be used (all other things being equal). At any rate you then decide what you want to do after a timeout. One possibility is to close the socket because to you that timeout means it is abandoned.
    2) setSoTimeout of ServerSocket applies to the accept* method. setSoTimeout of Socket applies to reads from that sockets input stream. Neither of those apply anything to all connections.
    I think the better way would be to write a timer or something for each connection No setSoTimeout is correct. You will also then need to actually attempt to read something for that timeout exception to ever be thrown.
    As far as the bandwidth question goes, you will need to define your goals better. Please do not just restate "control bandwidth" because that is not actually a very specific goal. Do you want to limnit the bandwidth used at one time (tricky) or do you want to limit the total bandwidth used. Either way requires some work but they are different things.

  • Simplest possible client-server for file sending...

    Hi im trying to create a simple client-server application using sockets.
    All i want the server to do i listen for the client to send him a file.
    Then maby later i'll implement some other stuff like resuming and stuff like that.
    And so the client application is only supposed to send a specified file to the server...
    However, all the examples and tutorials i've found on the net are either to complex or only dealing with textfiles. I dont need the client to specify what type of file it is just send it in byteform or whatever so that the server can write it to disk.
    I get a migraine from all the different types of input/output streams and i dont know which one to use and so on.
    If anyone has a good tutorial or example code somewere (seems to me this should be considred very basic stuff) please enligthen me :-)
    all help will be appreciated
    thanx
    /Eric

    Yep, O rielly - Networking for Java, not sure exact title, or any basic JAva network book. They start out with a simple app and over chapters add to it, you could stop where you want.....

  • Help needed on TCP/IP Multi-port Client-Server

    Hi all, I am trying to develop a client-server application to stream some data over a few random port numbers (defined by myself) to stream data over to the TCP server (i.e another computer) in LabVIEW. So far, I have created my application using the NI examples for "Simple Data Client + Server" and it works fine. I also understand that the "TCP Listen" VI is only able to listen for 1 TCP connection only and a way around this is to use queueing idea to receive & process the incoming data.The downside to the idea is that the "base port" (i.e initial port) needs to be the same (on every TCP client) with the TCP Server and it is not fit for the purpose I intended.
    Basically on the TCP server side, i need to chart/monitor the data on different port numbers that is being streamed real-time from the one TCP client computer. Is this possible in LabVIEW?
    Can anyone (incl. NI gurus) advise and point me in the right direction?
    *lost*
    Solved!
    Go to Solution.

    Hi
        http://zone.ni.com/devzone/cda/epd/p/id/2739 Here you can download that component.But you can also use TCP icons which is available in Data Commmunications>Protocals>TCp for communication and to read and write data use variant to flattened string. I have attached a small example where i will transfer a constant string to the host PC to check the link between client and the server. Hope this helps you.
    Attachments:
    TCP Comm.zip ‏47 KB

  • Client Server Chat program

    In a console based Client Server application I used BufferedReader
    & BufferedWriter objects to read & write from the socket's i/p & o/p
    streams.. But the same doesn't work in a GUI based env...(using Frames)
    However readUTF() & writeUTF() with DataInputStream & DataOutputStream
    works.. Why BufeeredReader/Writer doesnot work ?

    You must be doing something different. Thankfully, neither the streams nor the sockets have any idea that there is a frame in existence.

  • Client/server application (Help me)

    I have a client server application.In the client part i send data to the server and the server receive data. After receiveing data server also send some data but the client can't capture data. Anyone please tell me what is the problem?
    I am giving the sample code here......
    I am thinking actually the problem is in the client side.......
    Server
    out = new DataOutputStream(client.getOutputStream());
    input = this.client.getInputStream();
    byte[] data=new byte[input.available()];
    input.read(data);
    byte[] sdata=new byte[3];
    sdata[0]=1;
    sdata[1]=2;
    sdata[2]=3;
    out.write(sdata);
    Client
    How can i implement my client to send and receive at a time??

    Thanks all of u.
    I have solved the problem.
    Now i have another problem.In the Client side I have used DataOutput
    Stream(for sending) and InputStream(for receiving).
    With the InputStream i am capturing data by this way.....
    int dataSize=is.available();
    int kkk=0;
    boolean hasSize=true;
    while (kkk<=0) {
    dataSize = is.available();
             if (dataSize != 0 && hasSize) {
                          byte[] dat = new byte[dataSize];
                          is.read(dat);
                           String s = new String(dat);
                           System.out.println("Capture:" + s);
                           System.out.println("data ssss: "+dataSize);
                           hasSize=false;
                           kkk=9;
                       }//End of if
      }//End of while
                     Here is the problem. If I am sending from the server data size less 4000 byte then the client can easily capture the data. But when i am sending the data which is very very large such as 70,000 bytes then it creates a problem.
    My target is simple. I want to capture the whole data that is send by the server . then want to keep the data in a byte array which size will depend upon the receiving data.
    How can i do that??

Maybe you are looking for

  • Program code and transaction code  for handling unit detail

    Developed a SAP Script for the Handling unit details. Handling unit details is a document which has the details of materials, packaging materials and the level of packing. This Handling Units details will be issued to the customer at the time of deli

  • Itunes wont download propley

    When i had to reload my entire hp I had itunes which worked great. Now when i download it to the newest version it will stay on the quicktime download for hours which shouldnt happen. I never even had the chance to open itunes becuase of when it was

  • Java Class (Compiled with JDK6_u12) that works with UCCX 9.0.2, don´t work with UCCX 10.5

    I have a Java Class (Compiled with JDK6_u12) that works with UCCX 9.0.2, after upgrade it don´t work with UCCX 10.5 I get the error message: "Failed to access the WSDL at: https://www.brightnavigator.se/brightservice/brightservice.asmx?WSDL. It faile

  • How to extend analog line using VoIP with SPA8800

    I would like to use a SPA8800 to make an analog line available to a VoIP phone (because at the location of the phone only LAN is available and no phone line). This is, when the line rings, the VoIP phone should ring. It would be nice to have if the V

  • I don't want Mavericks anymore.

    I don't want Mavericks anymore.  How do I get rid of it and go back to 10.6.8?  I have applications that won't run on Mavericks now, and I don't have a Snow Leopard installation disc.  I wasn't thinking and I did not back up my files with time machin