Sockets behave differently on Windows

I am writing a program that communicates from C to Java via a socket. The C program forks and execs the Java program. That way I can do the GUI in a platform-independent manner. It works great in OS X and Linux. But when I try it in Windows (using the Windows sockets and spawnlp), the Java half of the program sits there using 100% cpu until I close the socket. I do not get this cpu usage on the other platforms.
Surely Java in Windows does not poll the socket? So what could cause this?
Here is my socket class:
* PlayServer.java
* Created on February 18, 2007, 5:39 PM
* This class creates a socket server to listen for TKF input
* Author: James A. Rome
* All incoming commands are terminated by a #
* This Socket server understands certain commands:
* Incoming commands:
* #f filepath The name of the tkf file to use as an input source
* #c closes the socket
* Outgoing commands:
package com.sciend.tekplot;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
* @author jar
public class GpcSocketServer {
private transient ServerSocket server;
private transient Socket socket;
private transient InputStream in;
private transient OutputStream out;
private static String str = "OK" ;
private transient Vector<InputData> data = new Vector();
protected final int BEFORE = 0;
protected final int GOT_TYPE = 1;
protected final int IN_MESSAGE = 2;
protected final int DONE = 4;
private volatile Thread t;
private volatile ReadSocket r;
/** Creates a new instance of GpcSocketServer on the default port */
public GpcSocketServer() {
startServer(9999); //default port
* Creates a new instance of GpcSocketServer on the given port
public GpcSocketServer(int port) {
startServer(port);
private void startServer(int port) {
try {
server = new ServerSocket(port);
socket = server.accept();
setIn(socket.getInputStream());
setOut(socket.getOutputStream());
// Send an OK to the client
getOut().write(str.getBytes());
// We next need to start the socket reader
r = new ReadSocket();
t = new Thread(r);
t.start();
} catch (IOException ex) {
ex.printStackTrace();
* Stop the socket server
public void stopServer() {
System.err.println("Stopping Java socket");
try {
r.cancel();
server.close();
catch (IOException e) {
e.printStackTrace();
* Get the last piece of data
public InputData getLastData() {
int size = getData().size();
return getData().get(size - 1);
* Get the first data of type t
* @param t - the code for the data type
public InputData getFirstDataType(char t) {
int size = getData().size();
for(int i = 0; i < size; i++) {
if(getData().get(i).getMessageType() == t) {
return getData().get(i);
return null;
* Get the last data of type t
* @param t - the code for the data type
public InputData getLastDataType(char t) {
int size = getData().size();
for(int i = size-1; i >= 0; i++) {
if(getData().get(i).getMessageType() == t) {
if(t == 'c') { //turn off socket
stopServer();
return getData().get(i);
return null;
* A class to read the socket input and to put it into a Vector
private class ReadSocket implements Runnable {
ReadSocket() {
public void run() {
int count = 0;
int msgCount = 0;
char type = '\0';
int nHashes = 0;
int state = 0;
int bp = 0; //buffer pointer
byte ch;
char chr;
String msg = "";
try {
try {
while (!Thread.currentThread().isInterrupted() ) {
if( (count = getIn().available()) > 0) {
// make array bigger than count in case more bytes are added between these steps
byte[] buffer = new byte[2* count ];
bp = 0;
// read the contents
count = getIn().read(buffer);
do {
switch(state) {
case BEFORE:
if(nHashes == 0) {   // read to the hash
while((ch = buffer[bp]) != '#') {
bp++;
if(bp == count)
break;
nHashes = 1;
bp++;
} else {
ch = buffer[bp++];
chr = (char)ch;
type = chr;
state = GOT_TYPE;
if(bp == count)
break;
break;
case GOT_TYPE:
// Toss any spaces before the message body
while((buffer[bp]) == ' ') {
bp++;
if(bp == count)
break;
state = IN_MESSAGE;
break;
case IN_MESSAGE:
while(true) {
ch = buffer[bp];
chr = (char)ch;
if(ch == '#') {
// end of message
state = DONE;
// create the new data structure
InputData id = new InputData();
id.setMessageCount(msgCount++);
id.setMessageType(type);
id.setMessage(msg);
// reset states and variables for new message
state = BEFORE;
msg = "";
type = '\0';
nHashes = 0;
getData().add(id); // Add it to the Vector.
bp++;
break;
} else {
msg = msg + chr;
bp++;
if(bp == count)
break;
break;
} while(bp < count);
Thread.sleep(1000);
} // end while(true)
} catch (IOException ex) {
ex.printStackTrace();
} catch(InterruptedException e) {
} // End of run
public void cancel() {
t.interrupt();
} // End ReadSocket
public InputStream getIn() {
return in;
public void setIn(InputStream in) {
this.in = in;
public OutputStream getOut() {
return out;
public void setOut(OutputStream out) {
this.out = out;
public Vector<InputData> getData() {
return data;
public void setData(Vector<InputData> data) {
this.data = data;
}

Use a BufferedInputStream around the socket input stream.
I'm not a fan of polling available() and sleeping. You're much better off using an appropriately sized buffer to start with and just calling read() and letting it decide when data is available. Consider the degenerate case where one byte at a time arrives 50ms apart. Your code will run 20 times as slowly as a simple read() call that blocks only until data is really there.

Similar Messages

  • Flash behaves differently in windows and linux ?

    There are some sites that flash doen't display too well (firefox/opera) in linux, but seems to work fine in windows. Is there a difference in the plugin for each OS?
    try this:
    http://www.asus.com/index.aspx
    Wait for the page to finish loading, and then hover your mouse over the "products" link at the top of the page.. the drop down menu is now masked by the "asus webcam notebook ad". This doesn't happen in windows.. I've tried both arch package and the default flash installer, but get the same results.
    Note: The drop down menu is visible if you use the flashblock extension and disable the ad.
    Thanks..

    yep, for some reason the linux flash plugin doesn't let the browser draw elements over the animations, which is especially annoying on websites like the one you mentioned where dropdown menus are used over a silly useless flash banner.
    there are a LOT of things wrong with the flash plugin. macromedia hasn't really addressed them in a long long time
    EDIT: which is why i wish the best of luck to the gplflash plugin developers.

  • Pdf duplication in Preview for Mac behaving differently

    When duplicating a PDF in Preview for Mac, a new image window would open that I could click on to select, then rename and save elsewhere. Just recently, seems like in the last few days, Preview now behaves differently. Now when I select duplicate, a duplicate document is created in the same window but shows as a thumbnail in the sidebar. This is confusing as it appears that Preview is trying to create a duplicate of the document at the end of the original. I don't appear to have received any updates from Apple that would account for this sudden change in behaviour (shows Preview last modified 18th November). I don't appear to be able to change this in Preview's Preferences. Can I revert Preview to the previous behaviour? (I'm using latest version of Preview in Yosemite on a 24" iMac).

    I always find that Preview can garble certain graphic elements or even slightly alter the over-all color of the PDF. However, I also find it is a lot quicker to deal with PDFs, especially when it comes to printing. Sometimes I get a PDF that I send to print on our Canon copier and I end up canceling the print job after 10-15 minutes because it's still processing. I open that same PDF in Preview and it prints in less than a minute. The same can be said of InDesign so on certain jobs I end up exporting as a PDF and printing from Preview. This might say a lot about Adobe's Printing Engine... (sorry, off-topic)

  • NavigateToURL behave differently in adove air

    Hi All,
    I have used navigateToURL in flash to navigate to a dirrerent URL and this works fine in the browser but when I used it with my adobe air application it behave differently. I have used "_SELF" as the target but in AIR, the new URL still open up as a new window. Is anyone has this same problem? How can i open the new URL in the same window? Please find below my flash code. Im using flash CS3 professional.
    var url:String = "http://localhost/Flash/login/welcome.php";
    var request:URLRequest = new URLRequest(url);
    try {               
           navigateToURL(request, '_SELF'); // second argument is target
    } catch (e:Error) {
      trace("Error occurred!");
    Thanks In advanced,
    best regards,
    Niroshan

    Hi All,
    found the answer. "_SELF" should be "_self" (simple letter).
    Thanks,
    best regards,
    niroshan

  • Fonts behave different in Photoshop in comparison with Illustrator

    I have a problem: it seems that some fonts behave different in Photoshop CS than in Illustrator CS on my Windows XP. Where Illustrator opens a vector (Ill) EPS file correct Photoshop shows me wrong characters sometimes: for example: an é becomes a wrong character: Capital O with a stroke through it. Frutiger was used.
    My question is: where does Photoshop behave different reading fonts in comparison with Illustrator?

    Perhaps you forgot to embed the font?
    Here comes an example, using characters  with accents.
    The font is GillSans-Schoolbook. The font or subset is embedded.
    The file extension TXT should be replaced by EPS after downloading.
    The EPS doesn't contain a preview image.
    The file is correctly handled by
    Photoshop CS2 (opened)
    InDesign CS2 (placed)
    Illustrator CS2 (opened)
    PSAlter (PostScript interpreter by Quite)
    All characters with accents are missing in
    Word 2007 (insert graphic)
    http://www.fho-emden.de/~hoffmann/buffel-7-sRGB-Dokument.txt
    Best regards --Gernot Hoffmann

  • Different browser windows share the same JVM

    Hi there !
    Running the same applet in different browser windows
    (Netscape 4.72 - Plug-in 1.2.2) appears to use the same JVM. When I see the process list from the OS (Windows Task Manager) I see only one Netscape Process.
    This is causing me a lot of problems, because the applet opens a socket connection with the server.
    Since all applet instances running in different browser windows each one, are executing on the same JVM, all messages they send to the server goes through the SAME socket connection, turning the server in an inconsistent state.
    Is it possible to start a completly new browser
    process in order to have each applet instance running in a different JVM ?
    TIA for any help

    Not much help for you but I've had the same problem over here ... and we could find nothing to improve this.

  • Mac and iPhone4 contact searches behave differently

    I have ~1000 contacts. One of them has an email address beginning with "c.s". Searching my mac address book for "c.s" narrows it down to that one contact. Searching iPhone contact for "c.s" gives a list of dozens of names that start with "c" and "s". Is it treating the period as a wild card?
    Related search problem: one of my contacts' email addresses starts with "diz". Searching my mac address book for "diz" narrows it down to that one contact. Searching iPhone contacts for "diz" yields nothing.
    Why do the mac and iPhone searches behave differently?

    "Powerpoint in fact is unable to play any video files, it can only play still images and sound files, as only these files can be embedded."
    The mac version CAN play videos inside PPT right on a slide. They are linked, but they still play ON the slide. Basically anything the QT player can play, ppt can play right on the slide. I assumed PPT for windows could do this with formats OTHER than QT.
    You're saying that NO VIDEO FORMAT IN EXISTANCE can play ON a slide in PPT for windows? I find that hard to believe.
    I've seen many folks post here suggesting AVI works just fine and can be played right on the slide in PPT for Windows. Mpeg1 is normally 320x240 and well, honestly it looks like crap on a 1024x768 screen (and most people these days do NOT want to show a 320x240 movie at regular size on a large slide), so I stand by my comments made previously, unless someone can post that they tested an AVI and PTT for windows actually bumps you OUT of ppt and into a player (full screen or not). I just can't imagine that's what it's doing. QT on the other hand, is pretty much broken except in the way you described, playing it in the QT player, which is why no one wants to do that.

  • How to use Different Main Windows in Multiple pages to print internal table

    Hi experts,
    I have a problem regarding how to have multiple different main windows in  smartforms..the problem is that i want to print an internal table in the third page of the smartform and that table can have dynamic values ..sometime it may have more than 400 values also which can not be printed in one or two pages ...
    so to accomplish the same what i did was..
    i tried creating a new main window in the third page but it is throwing an error saying two main windows not allowed and i also tried by copying the first page's main window but it is just repeating the same content what was there in second page..
      i also tried by creating a secondary window in the third page and in that  window i tried giving my internal table and tried by giving the next page to itself but  that also is not allowed and it throws an error saying a page without a main window cannot point to itself as a next page....
    i also tried using a secondary window and in that window i was trying to display the internal table but it is only showing third page content and fourth page itself  was not created....although in my next page field value of the third page , i have given  the third page itself as a next page ....but this also is not working ,.....
    please suggest how to have different main windows(not copy of first main window) in smartforms in order to display the dynamic contents of an internal table

    HI ,
    Just check with your smart styles with assigned  paragraph  allignment   .
    Try to create character style  with your required  font ,size and  Allignment  .
    Hope u this will solve your issue  .
    Let me know if any concerns......
    Regards,
    Lokesh

  • I would like to open different Safari windows in different Spaces

    I would like to be able to open different Safari windows in different Spaces. They guy at the Apple store told me this was impossible, but I am 99% sure that I accidentally had it working this way before I realized what Spaces was, but now that I have set my Spaces preferences, I cannot get it to work for me.
    Ideally, my husband could use one space - he only uses Safari. And I could use the other Spaces for my various applications, including Safari.
    Any suggestions appreciated!

    I do it as follows.
    I don't have Safari assigned to any (or all) spaces. I don't have the little checkbox checked at the bottom of Spaces preferences ("When switching to an application...").
    In a given space I click on Safari in the dock. This makes it the active application. Of course, if a window is already open in that space it will come to the front. But suppose there isn't a window open. I then ask for a new window (via the File menu, or via command-n). Voila. That window is in that space. You can do this in any space and the windows stay where you created them.
    (A shortcut is simply to control-click on the Safari dock icon and select "New Window".)
    charlie

  • Iam not able to share internet in windows 8 from my macbook air...though my iphone ipad is connected to the hotspot well..tried everything but it seems to be different from windows 7  and other microsft operating systems setting. help!!

    Iam not able to share internet in windows 8 from my macbook air...though my iphone ipad is connected to the hotspot well..tried everything but it seems to be different from windows 7  and other microsft operating systems setting. help!!

    Ask on a Windows forum since that's what you're having a problem with.

  • VSYNC in games working differently in Windows 7 and 8.1?

    So the problem is that VSYNC option in all my games is working totally different in Windows 7 and 8.1, and I want to know what is responsible for this.
    In Windows 7 it working like it should be - limiting frame rate to the screen refresh rate (60Hz in my case).
    But in Windows 8.1 its limiting GPU usage and randomly cuts frames to 40 or 48 for instance, instead of 50 or 55 with 99-100% GPU usage.
    Here's the GPU usage graph in Windows 8.1, left part with VSYNC on and the right one is OFF.
    http://i.imgur.com/ieAMIkn.jpg
    Could someone please tell me why this is even happening?
    SPECS: i7 3230QM, 8GB RAM, GeForce GT 650M SLI, Windows 7 SP1 / Windows 8.1 U1.

    Same drivers, same settings, different results.
    For example:
    Windows 8.1:
    2014-07-26 21:13:46 - Blackguards
    Frames: 2840 - Time: 60000ms - Avg: 47.333 - Min: 29 - Max: 51 - VSYNC ON
    2014-07-26 21:15:48 - Blackguards
    Frames: 3518 - Time: 60000ms - Avg: 58.633 - Min: 30 - Max: 64 - VSYNC OFF
    Windows 7:
    2014-07-26 21:20:44 - Blackguards
    Frames: 3474 - Time: 60000ms - Avg: 57.900 - Min: 32 - Max: 60 - VSYNC ON
    2014-07-26 21:23:11 - Blackguards
    Frames: 3569 - Time: 60000ms - Avg: 59.483 - Min: 31 - Max: 64 - VSYNC OFF

  • How to print line item 2times in two different main window in Sap Script

    Hi,
    I am designing check printing form using Sap script. I need to print line items 2times in different 2main window.can yu pls explain  how print like this.
    JK

    i cud not get ur query..pls elaborate

  • The same code behaving different in two files.

    The same code behaving different in two files.
    in pro*c file it is returning rows
    in sql file it is not returning any rows.
    please suggest me.
    regards,
    prasad.

    please find the code.
    sql_stmt := 'SELECT rNum, dpcCode, sID, hDate, fBlock, '||
    'lBlock, recQty, fID, fName, ' ||
    'tSeqNo, sType, tDate, fStatCode, pDate, recCount, r ' ||
    'FROM (SELECT rownum rNum, DPC_CODE_ORIG dpcCode, ' ||
    'SENSOR_ID sID, ' ||
    'to_char(HEADER_DATE, ''YYYYMMDDHH24MISS'') hDate, ' ||
    'FIRST_BLOCK_NUMBER fBlock, ' ||
    'LAST_BLOCK_NUMBER lBlock, ' ||
    'RECORD_QUANTITY recQty, ' ||
    'FILE_ID fID, ' ||
    'substr(FILE_NAME,1,30) fName, ' ||
    'TRACE_SEQUENCE_NO tSeqNo, ' ||
    'SENSOR_TYPE sType, ' ||
    'to_char(TRAILER_DATE, ''YYYYMMDDHH24MISS'') tdate, ' ||
    'NVL(FILE_STATUS_CODE, ''NL'') fStatCode, ' ||
    'to_char(PROCESSED_DATE, ''YYYYMMDDHH24MISS'') pDate, '||
    'NVL(RECIRCULATE_COUNT,0) recCount, ' ||
    'ROW_NUMBER() ' ||
    'OVER(ORDER BY TRAILER_DATE DESC, LAST_BLOCK_NUMBER DESC) r ' ||
    'FROM logfc10t ' ||
    'WHERE DPC_CODE_ORIG = :IN_DPC_CODE ' ||
    'AND SENSOR_ID = :IN_SENSOR_ID ' ||
    'AND (((TRAILER_DATE <= TO_DATE(:IN_TRAILER_DATE, ''YYYYMMDDHH24MISS''))' ||
    ' AND (LAST_BLOCK_NUMBER < :IN_BLOCK_NUMBER)) ' ||
    ' OR (TRAILER_DATE < TO_DATE(:IN_TRAILER_DATE, ''YYYYMMDDHH24MISS'')))) ' ||
    'WHERE r = 1 ';

  • How to display the same content in the two different main windows?

    Hi experts,
    How to display the same content in the two different main windows?
    Thanks in advance.
    sarath

    Hi
    Sorry but you can't have two main windows in sapscripts.
    Regards
    Gregory

  • Why Reports format behaves different in Excel and browser(if desformat=html or pdf)?

    1-Why Reports format behaves different in Excel and browser(if desformat=html or pdf)?
    2-I made three queries Q1,Q2 & Q3 and linked them with proper field links but suppose Q3 returns no records for some Q1&Q2 records & when the report runs for delimited options it reflects only those records as output for which all the queries return records(if Q3 returns no record then the related records from queries Q1,Q2 don't reflect) while the output in desformat=html or pdf is ok..
    can you please resolve my problems
    ( I have installed patch 5a in my report server machine)
    Thanks & Regds.
    Suneel
    null

    What do you mean by "different"? (In our
    experience, Oracle html output has too many
    columns, which are not visible in the
    browser but are obvious in Excel.)
    We build our own html programmatically, so
    that Excel matches the browser more closely.
    -- Allan Plumb

Maybe you are looking for

  • Adobe Muse - Menu Bar Customization

    I am new to muse and have made a couple of test sites. I am not working on my first Muse site and running into the problem of customizing my menu bar. The bar no longer shows up as 4 different sections. It comes up as one big one. How do I add more s

  • Dynamic configuration not working in Java mapping

    Hi All, I have a scenario where i  am using java mapping. In this i am doing following 1)Read file name from input message header 2)set file name in output message Header 3) set Directory name in output message Header i  have used following code .. b

  • "Invalid Expression " Error with Refreshing variable

    Hi When ever i try to validata following query in Refreshing tab of a variable, I am getting invalid expression error select USER_NAME from SNP_SESSION where SESS_NO = <%=odiRef.getSession()%> if i use following Query select STEP_MESS from <%=snpRef.

  • HT3887 why do i keep losing my keyboard, I've changed batteries which are now 100%?

    why do i keep losing my keyboard, I've changed batteries which are now 100%?

  • Help with OutOfMemoryError

    hi, our initial scenario is as follows. we were running a jboss server with a single bdb environment with the default memory setup (60% of vm space). the vm is allocated about 1GB of memory on a 4GB machine. during setup, we run an operation which pu