Windows socket funnies

Hi
Using Javaws to run an application under Windows does something funny with the socket I create to my server. I establish a connection, and can see it on both client & server side with netstat, but it doesn't seem to be able to read server responses. The client can however talk to the server. On Linux, it works beautifully. Is there anything I should know about Windows, JavaWS & sockets perhaps? Do I need to do something differently with the thread that initiates the connection? Any ideas at all please? I can't post code right now, but hopefully there's a simple gotcha I'm not aware of.
Thanks a ton guys :)
Ciao
Zak

I've NEVER had any socket funnies in JWS. We are developing a quite big application using even pools of sockets to connect to the server, and never had any problems regarding JWS. Also, I can indeed see my sockets with netstat.
Did you sign your application? Is the all-permissions flag set? Please give more information about stack traces and such... in the last consequence, if you really WANT help, you should give some test case to the public...
Maybe there's a personal firewall sitting on the windows machine?
You should give tcpdump a try... (there's a w32 port :-))
Patric

Similar Messages

  • The system cannot find the file specified.Windows sockets error code:2.

    Hi All,
      I am on MDM 5.5 SP6.
      I am getting the following error message when trying to logging in to the DM.
    The system cannot find the file specified.Windows sockets error code:2.This application will now exit.
    Runtime Error :
    Program C :\Program Files\SAP MDM 5.5\Data Manager\Datamanager.exe
    R6025.
    -Pure virtual function call.
    And in console also the MDM server is stopped after getting the above error message.
    Can anybody tell me what could be the problem?
    Thanks & Regards
    Sireesha.

    Hi Sireesha,
    According to me, there can be 3 problems,
    1. Kindly check whether the MDM server is stopped. If it is, then restart the MDM Server and Load the repository with Update indices.
    2. If this error is coming with every repository, the problem will be either in the Version mismatch of the Server and the GUI's you are using. Kindly ensure that the versions for the MDM server and the MDM Gui's Match.
    3. If only Data manager Client is giving the problem, then you can un-install and install the DM GUI again.
    Along with this, please refer to the link below :
    [[The system cannot find the file specified.Windows sockets error code:2.;]
    Hope it helps.
    Thanks and Regards
    Nitin jain

  • UDPWrite in a loop. "A Windows Sockets function call returned an unexpected error."

    Hello together,
    i use UDP Support Library in NI CVI 9.0. When i wait for receiving a packet at the pc to send then a packet from the pc, the functions UDPRead and UDPWrite work fine. If i want to test the maximum throughput, i put the UDPWrite in a loop, but then an error occurs. It is "kUDP_UnexpectedWinsockError"
    Error Popup:
    "NON-FATAL RUN-TIME ERROR:   "main.c", line 53, col 22, thread id
    0x00000C18:   Library function error (return value == -6822
    [0xffffe55a]). A Windows Sockets function call returned an unexpected
    error."
    Line 53:
    status = UDPWrite (channel, 60100, "192.168.1.10", pOutputBuffer, 1458);
    the whole loop:
    while(1)
    status = UDPWrite (channel, 60100, "192.168.1.10", pOutputBuffer, 1458);
    counter++;
    if(counter>50)
    break;
    else{;}
    The error occurs after 3-16 packets have been sent. If i step through the programm, no error occurs. So i guess its because the UDPWrite command is invoked too fast. pOutputBuffer has static data. I could use a delay in the loop, but then i dont know how to configure for maximal throughput.
    Any ideas how to avoid this error?
    Regards Florian

    Hello and thank you for your answer. Sorry that i reply a month later.
    I dont know what you mean by "let 'er rip approach". Do you mean something like:
    status = UDPWrite (channel, 60100, "192.168.1.10", pOutputBuffer, 1458);
    if(status==0)
     counter++;
    else
      Delay(0.00005);
    I did not yet try to put the packet number in the payload, but there is just a 30 cm crossover cable between the two devices, no switch, no router. So the sequence should not be interruptet. And even if they arrive in chaos, i dont mind.
    I have contacted the NI support 2 weeks ago, but no response yet.
    I did some tests with a delay between the execution of UDPWrite(). The code:
    float time = 0.0;
     for(i = 1; i < 1000; i++)
      status = UDPWrite (channel, 60100, "192.168.1.10", pOutputBuffer, 1458);
      time = 1.0 / i;
      Delay(time);
    The results:
    For i between 1 and 1000: no error, the speed of the last ten packets was about 6.5 MBit/s
    For i between 1000 and 2000: error occured at i = 1585 (variable time in Delay was 0.0006313), the speed of the last ten packets was about 8 MBit/s
    Then i put some constant values in Delay and ran 100 UDPWrite iterations:
    Delay(0.0006): 7.48 MBit/s
    Delay(0.0001): 10.7 MBit/s
    Delay(0.00001): error occured at i=31, speed of 31 packets was 12.0 MBit/s
    Delay(0.00008): 100 of 100 packets, speed 10.9 MBit/s
    Delay(0.00005): error at i=41, speed of 41 packets 11.1 MBit/s

  • Unrecognized Windows Sockets Error: 0: JVM_Bind

    I'm not entirely sure if I compacted this well enough, but after class declaration and method calling, it is essentially what my program does.
    Server server = new Server(); // Creates a ServerSocket and binds it to a port.
    Client client = new Client(server.getSocketAddress());
    public Client(SocketAddress bind)
         try
              socket = new Socket();
              socket.bind(bind); // Problem here
              recieve = new Scanner(socket.getInputStream());
              send = new Formatter(socket.getOutputStream());
         catch (IOException e)
              e.printStackTrace();
    }Running the above code produces the following exception.
    java.net.SocketException: Unrecognized Windows Sockets error: 0: JVM_Bind
         at java.net.PlainSocketImpl.socketBind(Native Method)
         at java.net.PlainSocketImpl.bind(Unknown Source)
         at java.net.Socket.bind(Unknown Source)
         at GameObjects.PlayArea$Client.<init>(PlayArea.java:318)
         at GameObjects.PlayArea.<init>(PlayArea.java:48)
         at MenuStates.GamePlayState.initializePlayArea(GamePlayState.java:90)
         at MenuStates.CreateGameState.mouseClicked(CreateGameState.java:106)
         at Manager.GameManager.mouseClicked(GameManager.java:428)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Window.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)I don't even know what this exception is, and I can't find anything that will really tell me what is going on. Can anyone tell me what is happening here?
    I know that this question isn't directly related to Game Development, but I am using it in a game program, and I posted this question in the Network forum, and they flooded my topic with useless messages, and the only person who actually answered my question was extremely vague about it, even after I asked him to clarify. I am hoping that the good people of this forum will be more helpful.

    In some cases, the server socket used to need more time to be available. If you run several test, you need time to reuse the same port (for Windows 7). I could try the following code:
    Server server = new Server(); // Creates a ServerSocket and binds it to a port.
    Thread.sleep(500); // Waiting for server to be available
    Client client = new Client(server.getSocketAddress());
    public Client(SocketAddress bind)
         try
              socket = new Socket();
              socket.bind(bind); // Problem here
              recieve = new Scanner(socket.getInputStream());
              send = new Formatter(socket.getOutputStream());
              Thread.sleep(500); // Time to execute the sme port in another test.
         catch (IOException e)
              e.printStackTrace();
    }

  • Unrecognized Windows Sockets error: 10106: create

    Am getting the following error when I use tcp-mon to sniff the HTTP traffic. Same when I use SOAP-UI.
    I'm using windows 7 and using "jdk1.6.0_13". Any help on this pls .
    java.net.SocketException: Unrecognized Windows Sockets error: 10106: create
    at java.net.Socket.createImpl(Socket.java:388)
    at java.net.Socket.<init>(Socket.java:362)
    at java.net.Socket.<init>(Socket.java:180)
    at org.apache.ws.commons.tcpmon.SocketWaiter.halt(SocketWaiter.java:98)
    at org.apache.ws.commons.tcpmon.Listener.stop(Listener.java:543)
    at org.apache.ws.commons.tcpmon.SocketWaiter.run(SocketWaiter.java:87)

    Winsock error 10106. 8 seconds in Google. Looks like something wrong with your operating system installation.

  • Unrecognized Windows Sockets error...

    Hello everybody!
    I am encountering the following problem, when I try to run a program which wants to access the internet. I pasted an extract from the source code here, which I think includes the critical lines:
    import java.net.*;
    import java.io.*;
    class FindLinks {
    public static Vector findLinks (String address) throws Exception {
    URL u = new URL(address);
    InputStream ins = u.openStream();
    InputStreamReader isr = new InputStreamReader(ins);
    BufferedReader webPage = new BufferedReader(isr);
    When I run the complete program, I get the following message:
    Exception in thread "main" java.net.SocketException: Unrecognized Windows Sockets error: 10106: create
    at java.net.Socket.createImpl(Socket.java:313)
    at java.net.Socket.connect(Socket.java:424)
    at java.net.Socket.connect(Socket.java:376)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:139)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:386)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:602)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:303)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:264)
    at sun.net.www.http.HttpClient.New(HttpClient.java:336)
    at sun.net.www.http.HttpClient.New(HttpClient.java:317)
    at sun.net.www.http.HttpClient.New(HttpClient.java:312)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect HttpURLConnection.java:481)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:472)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:574)
    at java.net.URL.openStream(URL.java:960)
    at FindLinks.findLinks(FindLinks.java:10)
    at FindLinks.main(FindLinks.java:47)
    I am using the new Java SDK 1.41 on a Windows XP machine. Does anyone has an idea what might be causing this problem?
    Kind regards
    Linus

    I know, but you triple posted

  • A way to disable NAGLE of windows SOCKET

    I know that if I use VISA socket, I can change the value of VI_ATTR_TCPIP_NODELAY attribute and enable/disable NAGLE algorithm. How can I do the same thing using standard windows socket? say when I have established my connection by ConnectToTCPServer command.

    Okay, now I am getting really confused... Sorry, it's partly because of my lack of experience... but I'll go ahead and say how I again bumped into a dead end.
    I found no winsock2.h under my National Instruments\CVI85\sdk\include  (winsock.h exists though under this folder)      I also found no ws2-32.lib anywhere in under my National Instrument folder. But I found both of them under my MATLAB directory...
    So I copy-pasted winsock2.h into National Instruments\CVI85\sdk\include and #include <winsock2.h> in my c application. I also copy-pasted ws2_32.lib into National Instruments\CVI85\extlib, and added it to my project.
    When I compile my code this way, it gives me lots of "redefinition of macro " errors, for example for 'WSAEINTR', 'WSAEBADF' and so on...
    If I change #include <winsock2.h> to #include <winsock.h>, the compile works fine, but linker gives error "Read error"...
    I have no idea what this means and how it can get solved. Thanks again for your time.

  • Satellite L300 - T2FTP Windows sockets initialization failed

    After Login I get the following message:
    T2FTP Windows sockets initialization failed
    At the same time the system gives a message that it has found a new unknown hardware device and the driver should be installed.
    Before I did NOT add any new hardware device.
    Clicking the Start Button results only in a message: Windows Explorer does not react.
    It is impossible to call any other routine.
    Unfortunately I don't find my Recovery-CDROM.
    Is there any chance to save my system?
    Toshiba Satellite L300, Model PSLB8E
    Windows VISTA-32 bit

    Hi
    I think its operating system issue something, somewhere was going wrong
    I agree with Jeka. The Vista reinstallation would be the easiest and fastest way to get rid of this problem.
    If didnt get the recovery disk because the OS was preinstalled and there was an tool which allows you to create an own recovery disk.
    You should be able to recover the unit using HDD recovery
    Restart the notebook, press F8 and choose repair my computer.
    Then choose Toshiba HDD recovery.
    This would recover the OS again.

  • Vugen stopped working with Windows socket protocol

    Hi Everyone...
    I am trying to record windows client apllication with Windows socket protocol(Single). Its throughing following messange and crassed Vugen with the following message.
    If anyone know about how to proceed further can please let me know.
    Thanks,
    Sri

    Hi,
    Parallels is not an application I have so I can not test this further.
    I would think the answer may lie in the BootCamp forum where people may have tried the same thing as you or at any Parallels Forum you can find.
    (Start here as there are links to the unintegrated ones).
    7:32 PM Saturday; March 28, 2009

  • Unable to connect to the server - windows sockets

    //////socket connector method////
    bool SocketConnecter::connect(const std::string& ip, size_t port)
    size_t uport = htons(port);
    std::string sPort = toString(uport);
    // Resolve the server address and port
    const char* pTemp = ip.c_str();
    iResult = getaddrinfo(pTemp, sPort.c_str(), &hints, &result); // was DEFAULT_PORT
    if (iResult != 0) {
    Verbose::show("\n -- getaddrinfo failed with error: " + toString(iResult), always);
    return false;
    // Attempt to connect to an address until one succeeds
    for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
    char ipstr[INET6_ADDRSTRLEN];
    void *addr;
    char *ipver;
    // get pointer to address - different fields in IPv4 and IPv6:
    if (ptr->ai_family == AF_INET) { // IPv4
    struct sockaddr_in *ipv4 = (struct sockaddr_in *)ptr->ai_addr;
    addr = &(ipv4->sin_addr);
    ipver = "IPv4";
    else { // IPv6
    struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)ptr->ai_addr;
    addr = &(ipv6->sin6_addr);
    ipver = "IPv6";
    // convert the IP to a string and print it:
    inet_ntop(ptr->ai_family, addr, ipstr, sizeof ipstr);
    printf("\n %s: %s", ipver, ipstr);
    // Create a SOCKET for connecting to server
    socket_ = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
    if (socket_ == INVALID_SOCKET) {
    int error = WSAGetLastError();
    Verbose::show("\n -- socket failed with error: " + toString<int>(error), always);
    return false;
    iResult = ::connect(socket_, ptr->ai_addr, (int)ptr->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
    socket_ = INVALID_SOCKET;
    int error = WSAGetLastError();
    Verbose::show("WSAGetLastError returned " + toString(error));
    continue;
    break;
    freeaddrinfo(result);
    if (socket_ == INVALID_SOCKET) {
    int error = WSAGetLastError();
    Verbose::show("\n -- unable to connect to server, error = " + toString(error));
    return false;
    return true;
    /////////Test stub////
    int main()
    title("Testing Socket Client", '=');
    try
    Verbose v(true);
    SocketSystem ss;
    SocketConnecter si;
    while (!si.connect("localhost", 9080))
    Verbose::show("client waiting to connect");
    ::Sleep(100);
    title("Starting string test on client");
    clientTestStringHandling(si);
    title("Starting buffer test on client");
    clientTestBufferHandling(si);
    si.sendString("TEST_STOP");
    Verbose::show("\n client calling send shutdown\n");
    si.shutDownSend();
    catch (std::exception& ex)
    Verbose::show(" Exception caught:", true);//always = true
    Verbose::show(std::string("\n ") + ex.what() + "\n\n");
    I am trying to connect to the server, but the connector method shows the message "unable to connect to server" 
    While debugging i found the iResult to be -1 which makes the socket INVALID_SOCKET
    Kindly help resolve this

    Hi askatral,
    connect function can return invalid_socket for many reasons, what does the function WSAGetLastError return?
    There are some Variables that I cannot find how it is declared, like "socket_" and "ptr". So I cannot check if there is anything wrong in your code.
    Maybe this sample in the document of connect function is helpful for this issue:
    https://msdn.microsoft.com/en-us/library/windows/desktop/ms737625(v=vs.85).aspx
    Best regards,
    Shu
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Unix to Windows socket

    I'm looking for a socket class or some such thing to use an external procedure running on Windows NT from Oracle running on Solaris. What is out there?
    Pat

    LabVIEW has both TCP and UDP functions. If you set up your unix program as a TCP/UDP data server, it's pretty simple to write a LabVIEW client and in fact, LabVIEW comes with a sample client program.

  • Windows socket initialization failed Error

     Hello,
    I have a truble with programming on MS visual c 6.0
    Followings are error message on MS visual c 6.0
    If i don't use DAQmxErrChk, error doesn't come out.
    If i use DAQmxErrChk just one line(or more), error come out like the figure.
    Please help me.
    Yongtae 

    Restack your tcpip, and make sure you are not missing the winsock dll. Quite often, restarting the windows machine would also help.

  • No internet connection on either x64/x86 flavor on Windows 10 -- Missing Sockets entries as well.

    Hi all,
    I was referred here from http://answers.microsoft.com site, by a Microsoft Support Engineer....
    I had (and still have virtual-box).  I have installed yesterday the VMware workstation as well (which apparently is not compatible with Hyper-V.
    I've installed both Windows10 Preview flavors under HYPER-V.  On either one, I cannot connect to the internet (and thus activate either).  The x64bit says it's missing files needed (I've 
    checked detailed view, it points to "missing windows sockets registry entries" and has 2 "?" marks under Device manager (one of which is the acpi) - Even after a fresh, SECOND, install.
    The x86 flavor, says i do not have valid ip.  (I had to make local user account because of the no internet access).  I went through the defaults while installing 
    (no motherboards drivers have been asked to be installed).  This is a Desktop computer with wired high-band routers.
    Can anyone suggest a solution for the connection?  (I now obviously also have the external switch and is is connected and i can surf on the primary Win8.1 OS).
    Do I really need BOTH VMware and Hyper-V installed / Which one is better for this specific problem..
    ANY help will be greatly appreciated.
    Update:
    I've took off Hyper-V completely.  Re-stared, Tried to set it up under VMware workstation, got the same results.  Either "no valid ip", or missing sockets.  (Vmware adapter is enables, but no connection in either ipv4 and
    ipv6.  Exactly the same
    happens with Hyper-V.
    With Utmost Respect,
    The motherboard is MSI.  The CPU is I-7.  6GB ram avail. 
    Kind Regards,
    Me.
    Update 2:
    Problem resolved.  Here's what i did:
    Completely removed the Hyper-V platform from Windows Featured.   Then rebooted.
    (Vmware services are still running but with no usage for now).
    Opted in the Enable PAE/NX under system/Processor tab in VirtualBox.
    Opted in the Enable VT-x/AMD-V & Nested Paging under system/Acceleration tab in VirtualBox.
    Created the Virtual PC  as VHD!!
    Both of the above -- are grayed out when the Hyper-V platform is installed and therefor will NOT allow Windows 10 Preview to either install well or connect and activate - until the Hyper-V is removed.
    Seems that taking OFF the native, built in Hyper-V Virtualization Platform altogether - Solved the issue.
    Just shows that  the respectable VirtualBox (v.4.3.12),
    Works like a charm where the other two platforms, Did not.  (Kindly note that the Hyper-V Switch, was installed with no evadent issues, it did show traffice - for a few seconds, then remained enabled BUT both IPv4 & IPv6 went to no connection).
    Windows managed to successfully Connect and auto activate -- on both x86 & x64 flavors.

    Use this set of drivers and put on FAT Flash memory card to access.
    They will work and better due to your having a 2011 model you should consider Lion OS eventually.
    Can't locate? the Apple Setup.exe or Bootcamp.msi (Bootcamp64.msi for 64-bit) will only be accessible when in Windows.
    http://www.apple.com/support/bootcamp

  • Change UDP Socket.ReceiveBufferSize under Windows

    I've previously used a LabVIEW LLB that allows customizing a TCP socket (TCP_NODELAY LLB) to enable and disable delayed acks. This NI LLB contains a pasword protected VI that returns a raw TCP socket ID that is in turn used as an input to a Call Library Function node. A previous post on the NI forums indicates to me that the Windows default buffer size is used (8192 ...
    I would like to increase the Socket.ReceiveBufferSize for a LabVIEW UDP Connection ID.
    MSDN Windows Socket.ReceiveBufferSize property info
    Now is the right time to use %^<%Y-%m-%dT%H:%M:%S%3uZ>T
    If you don't hate time zones, you're not a real programmer.
    "You are what you don't automate"
    Inplaceness is synonymous with insidiousness
    Solved!
    Go to Solution.

    Sorry for the confusing post. I'm using the LabVIEW UDP VIs. My situation is:
    I am running three UDP receivers (Reentrant VI & VI Server) using
    three point-to-point Gigabit Ethernet connections. I drop data when
    sending rates are > 2.4 Mbit/sec. Data is only sent in one
    direction. I have used a TCP version of my application where the CPU
    load is ~ 50%, with (of course) no dropped data because of TCP. I have
    also used TCP_Nodelay.llb to disable nagling, and see 80 to 90% CPU utilization.
    I've simply replaced the TCP Open, Receive and Close functions with UDP
    functions. While running, my CPU load fluctuates from 80 to 100%, and I
    drop data.  UDP has no sequencing or acks to manage, so I can't imagine
    why the CPU load would be higher AND that I would drop data. I've run
    the UDP version at half my goal (1.2 MBit/sec) without dropping data. I
    do use a 1 ms timeout on the UDP and TCP reads.
    I would like to use the same technique to retrieve a UDP raw socket ID, then use that ID to configure SO_RCVBUF instead of TCP_NODELAY to try and eliminate the data loss. I would like to increase the buffer size, or even possibly set it to zero after reading this CodeGuru forum entry.
    Message Edited by Phillip Brooks on 02-28-2007 10:13 AM
    Now is the right time to use %^<%Y-%m-%dT%H:%M:%S%3uZ>T
    If you don't hate time zones, you're not a real programmer.
    "You are what you don't automate"
    Inplaceness is synonymous with insidiousness
    Attachments:
    TCP_NODELAY.llb.gif ‏30 KB

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

Maybe you are looking for

  • Crystal Report Viewer Error Handling

    Dear All Thank you for your attention. I wrote a C# program for user to print out an order using WPF and crystal report viewer. Computer A is connected directly to the printer through USB. Computer B and C are connected to the printer through printer

  • Chinese character issue in BSP input text

    Hi Experts, We are using chinese characters for some text fields in BSP. That characters are displayed correctly in the BSP screen. But the same is converted as numbers and special character in backend and stored in the database table. When analyse t

  • Updated to IOS 5 and app icons are missing

    I upgraded last night and now some of my app icons are missing. If I do a spotlight search and find the app I can then launch the app from there but I would like to have the icon back to use rather than a workaround.

  • My photos are not importing properly into iPhoto! They import successfully but never appear in my library!

    Whenever I import photos recently they will be in the Last Import folder but when I click my photo library they are not in it. And then when I go back to last import they aren't in there anymore. I have already lost a lot of pictures since I always s

  • Unexplained network traffic

    I leave my MacBook Pro on all the time with normal energy saving preferences - computer sleep after 15 minutes, display sleep after 10 minutes. Since upgrading to Mavericks I've noticed an unexplained daily amount of about 150MB of network traffic on