Newbie Sockets Question

Hi - I'm new to Java and have been trying to create a class to encapsulate socket communication. It doesn't work and I don't understand why?
As I figure I've created and instance of SocketCommunication, called SetUpSocket (which works) and then called SocketSend to work on the mySocket instance. But my server never receives anything...
What am I doing wrong?
=================================================================
public class SocketTester {
    public SocketTester() {
    public static void main(String[] args) {
        SocketCommunication mySocket = new SocketCommunication("localhost", 4000, 4001);
        mySocket .SetUpSocket();
        String strReceived = mySocket .doSend("HELLO");
        System.out.print(strReceived);
=================================================================
import java.util.*;
import java.io.*;
import java.net.*;
public class SocketCommunication {
    private Socket inClient;
    private Socket outClient;
    private BufferedReader socketReader;
    private PrintWriter socketWriter;
    private String host;
    private int outPort;
    private int inPort;
    public SocketCommunication(String host, int outPort, int inPort) {
        this.host = host;
        this.outPort = outPort;
        this.inPort = inPort;
    public boolean SetUpSocket(){
        try {
            outClient = new Socket(host, outPort);
            outClient.setKeepAlive(true);
            socketWriter = new PrintWriter(outClient.getOutputStream());
            inClient = new Socket(host, inPort);
            inClient.setKeepAlive(true);
            socketReader = new BufferedReader(new InputStreamReader(inClient.getInputStream()));
        } catch (UnknownHostException e) {
            System.out.println("Error setting up socket connection: unknown host " + host );
            return false;
        } catch (IOException e) {
            System.out.println("Error setting up socket connection: " + e);
            return false;
        return true;
    public String doSend(String sendString) {
        String receiveString = null;
        try{
            socketWriter.print(sendString);
            socketWriter.flush();
            receiveString = getData(socketReader);
            if (null == receiveString) {
                System.out.println("no response");
        } catch (IOException e) {
            System.out.println("Error communicating: " + e);
        //receiveString = "test";
        return receiveString;
    public String getData(BufferedReader in) throws IOException {
        int iIncomingCharacter;
        StringBuffer sbMsgBuilder = new StringBuffer();
        String sMsg = null;
        while ( true ) {
            // Read character
            iIncomingCharacter = in.read();
            if ((iIncomingCharacter) == -1) {
                sMsg = "-1";
                break;
            // Append character to buffer
            sbMsgBuilder.append((char) iIncomingCharacter);
            // Test to see if "$END$\n" has been received
            if ((sbMsgBuilder.length()>6) && (sbMsgBuilder.substring(sbMsgBuilder.length()-6).equals("$END$\n"))) {
                // Convert buffer to string
                sMsg = sbMsgBuilder.toString();
                // Reset the buffer for next message
                sbMsgBuilder.delete(0,sbMsgBuilder.length());
                break;
        return sMsg;
=================================================================

>>>
Connecting of course requires something toconnect
"to".Indeed.
So are you saying ServerSocket is required?
I don't use ServerSocket when I connect to a
database. But there is still something to connect
"to".Yes, I know.
I'm talking specifically about the OP's case of Java talking to Java.
But in java you would need to use a server of some
sort although (guessing) for nio you need
ServerSocketChannel rather than ServerSocket. Still
a server though.I suspected as much. I just didn't know for certain that Socket didn't have a method to allow it to fullfil ServerSocket's role in some capacity. I wouldn't expect it, but I didn't know for sure and couldn't be bothered to check. I didn't look that closely at the OP's code and didn't want to send him off with bad advice if he was just doing something that was legit but outside my own knowledge.

Similar Messages

  • General place for newbie datamodeler questions?

    With the production release of SQL Developer Data Modeler I'd assume that this forum will draw a bunch of new users. Is there a better place to ask some pretty simple, newbie like questions that won't bother the more seasoned members?
    For instance, I am working in a Rails environment, which has some stringent naming conventions, one of which is that all of the primary key columns are numeric and called "id", with the foreign key linked columns called <table_name>_id.  When engineering a logical model to a relational model, the added foreign key columns are all "id#".  Is there a way I can define a naming rule to keep me from having to redo the relation column names?
    Also, we have a standard set of columns (mostly Rails related) which appear in every table. Can I define a generation rule which automatically includes these tables?
    Thanks

    Thank you. I will try changing that setting.
    IS there a setting which tells the relational model to automatically create pk and fk indexes? I haven't seen one, and manually setting them up is a tedious task. --sw                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Newbie script question... consecutive numbers with update.

    complete newbie type question... this is also my first post.  ( I am using CS3)
    does anyone have a script which can make it so I can add numbers into the text consecutively.
    for example, if this is my text "the big fat dog sat on the very wide mat, but was then displaced by a unfriendly cat."
    and I wanted to place a number 1, number 2, 3, etc at points in the text so it read, "the big fat dog1 sat on the very wide mat2, but was then displaced by a unfriendly cat3." but later wanted to add another number and have later numbers update themselves, so the text then said, "the big fat dog1 sat on the very wide mat2, but was then displaced3 by a unfriendly cat.4".
    by inserting the three, the previous three became four.
    Has anyone got something which might be useful in this regard.
    Many thanks
    Steve

    i wanted to avoid footnotes as they leave a bar at the bottom of each page.
    i wanted a script to do something similar to footnotes but not much further.
    does anyone have just a simple script that can do what I asked?
    Steve

  • Newbie XSan question - authenticating a computer from XSan Admin

    Hello - I have a very newbie XSan question!
    I have 2 computers that connect to an XSan. 1 I am having no problems with. The other I am unable to connect with.
    When I look in XSan Admin the 2nd computer (the one that is not working) is not authenticated.
    So I click on it and choose Authenticate. I enter what I know is an Admin username and password for the computer I am attempting to connect. The dot next to the computers IP turns green with 3 dots in it and then it turns gray again. It just does not connect.
    What is the problem?
    Is it licensing?
    Thanks
    Taj

    You need a different license ID for each machine, plus the admin machine. Do you have that?

  • Newbie socket read write question

    Hello all,
    I need to develop a simple client application in java using socket
    programming. The client will connect to a server implemented in VC++.
    The server part has been implemented so I need to develop only the
    client part.
    Could anybody help me with a simple program that sends data to the
    server and then prints out whatever the server sends back for the
    given request.
    The client and the server communicate using a specified format of bytes as shown below. I do not know how to read those bytes using the sizes as the token.
    I know how to connect to the server but I do not know the proper way of sending and receiving data.
    connection = new Socket(destination, port);
    outStream = new DataOutputStream connection.getOutputStream());
    //send the ID 1 to the server
    outStream.writeByte(1);
    //send the total packet size
    //send the data
    Thanks in advance
    Pertheli
    The client and server communicates with the following packet format
    shown below. Each packet will have header, size and data as shown
    PACKET
    offset(byte) contents
    0 byte PACKET ID
    1 byte PACKET length (motolora format)
    2 byte
    3 byte DATA * n (motolora format)
    4 byte
    5 byte ~ DATA
    n byte
    Now for a For say PACKET ID = 1
    we send the data to the server like
    0 byte (motolora format)
    3 byte
    Then from the VC server we recieve the data in the format such as
    0 byte Name
    43 byte
    44 byte Status

    Hi!
    Try this...
    Socket connection = new Socket(server,port);
    // use a Buffered*Stream as often as possible, because
    // of the IP Packet Lengths...It Increases the
    // network performance (but you DON'T need it)
    // you'll send bytes or messages to the server in
    // the OutputStream and receive answers from the
    // server in the InputStream
    int packetOutputBufferSize = connection.getSendBufferSize();
    int packetInputBufferSize = connection.getReceiveBufferSize();
    BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream(),packetOutputBufferSize);
    BufferedInputStream bis = new BufferedInputStream(connection.getInputStream(),packetInputBufferSize);
    // sending data through the socket
    // create your packet in a byte array
    byte[] output = new byte[<packet-lenght>];
    output[0]=<packet ID>
    output[1]=....
    bos.write(output,0,output.length);
    // receiving data from the socket
    byte[] input = new byte[<max-packet-length>];
    int read=0;
    int length=0;
    while ((read=bis.read(input,length,(input.length-length)) > 0) {
    length+=read;
    if (length>=input.length) break;
    // now your server output is in the bytearray 'input'
    If it isn't possible to set a max packet size, use a bytearray as buffer and write it content into a ByteArrayOutputStream, thats something like a resizable write-only byte array. (you'll get the full content of it by calling the method ByteArrayOutputStream.toByteArray())
    Maybe you want to check the packet content during receiving the bytes from the socket: Then you should use some read() method from the InputStream, but thats not very powerful.

  • This Newbie Has Questions

    Hi there. I am a newbie to Apple. I purchased the iBook last month and of course, when the MacBook (which had the features I wanted) came out, I rushed out and got one and I'm very pleased with my purchase - but I have a few "newbie" questions:
    1) Printing on a PC based Linksys seems to be a nightmare. I can't get anything printed on the shared HP 2600N and HP1012 printers. I literally have to disconnect them from the PC and plug the USB directly to my MacBook to print. It seems like there should be a better, easier and MacFriendly way of doing this - anyone have an easy solution?
    2) I'm going to purchase Windows XP so I can run my windows programs on this computer. Does anyone have any pre-installation advice?
    3) I have a blackberry device that worked fine with my iBook, but does not work with my MacBook - any suggestions or is there a software compatibility patch?
    4) I transferred everything from my old Mac to my new Mac with no problem. How can I migrate my contacts from Entourage to the Address Book?
    5) I notice that sometimes the MacBook "stalls" or doesn't work fast in some functions...is it just me - I expect the machine to jump quickly...but sometimes I get that annoying pinwheel when opening programs.
    Thanks for your help!

    1) Printing on a PC based Linksys seems to be a
    nightmare. I can't get anything printed on the
    shared HP 2600N and HP1012 printers. I literally
    have to disconnect them from the PC and plug the USB
    directly to my MacBook to print. It seems like
    there should be a better, easier and MacFriendly way
    of doing this - anyone have an easy solution?
    The problem is probably a driver issue.
    Printing to a printer on a XP PC from a Mac running 10.4.x
    http://www.ifelix.co.uk/tech/3015.html
    You may need to use a third-party driver such as the HPIJS drivers or the Gimp-Print drivers, but this is not the case with all printers.
    2) I'm going to purchase Windows XP so I can run my
    windows programs on this computer. Does anyone have
    any pre-installation advice?
    Ensure you get a full version (not an upgrade version) and it comes with XP SP2 already.
    Do not install Boot Camp on a critical machine and make regular backups of your data, this is beta software and there are bugs and issues.
    5) I notice that sometimes the MacBook "stalls" or
    doesn't work fast in some functions...is it just me -
    I expect the machine to jump quickly...but sometimes
    I get that annoying pinwheel when opening programs.
    Are these Universal or PPC only applications?
    iFelix

  • What is better???--sockets question

    I have a server that receives one client (one thread of them) per socket.
    Is it better to have all in the same socket?
    where is the bottle�s neck? in the processor or in the bandwith?

    ok
    and what is better for my server:
    1) receive each client in a different socket
    2)receive all clients in one socketAFAIK you would need a new port for each server socket. How then can your clients know which port to connect too? Therefore I think (2) is the proper solution.
    For a general implementation of a tcp server, have a look at my solution at http://www.ebi.ac.uk/~kirsch/monq-doc/monq/net/TcpServer.html . You can download the code by following the link at the bottom of that page. Comments/questions welcome.
    Harald.

  • Newbie wireless question (slightly off-topic)

    I didn't want to post this here as it's not entirely an Airport-specific question. I posted this to the iBook forums, but nobody there has answered so my apologies if this is not welcome here. (Any moderators can remove it if that's the case.)
    I've been using computers extensively for over a decade, but I'm a total newbie to wifi. I just set up a wireless network in my house and would appreciate some advice/feedback.
    My main concerns are whether or not my network is reasonably secure. I know there is no such thing as perfect security, but I don't know if what I've done is good enough or not.
    I don't have an Airport base station, but I do have a D-Link Airplus G and an Airport card in my iBook. I have WEP set up on the router and I have enabled MAC filtering, listing only my desktop and my iBook, excluding all others from the network.
    I'm fairly certain that nobody in my neighborhood is going to get into my machines this way or be able to sniff my network data stream, but am I right in assuming that nobody can "piggyback" on my Internet connection too? Presumably, if everyone but my own machines are MAC-filtered and kept out, then the Internet connection is also protected. Is that how it works?

    WEP and MAC filtering are better than nothing, but you can do better. These are my suggestions:
    1. Use WPA with a pre-shared key (PSK) and TKIP encryption on your Netgear router, along with an alphanumeric passphrase of at least eight characters not found in any dictionary. The equivalent setting on your Mac is "WPA Personal". Unlike WEP security (which an expert can crack in under half an hour), WPA security is currently unhackable by any practical means as long as you use a non-dictionary passphrase. One last point - WPA security requires all your wireless Macs to be running MacOS 10.3 or newer.
    2. MAC filtering is (these days) essentially useless as a wireless security method. Using "packet sniffing" of traffic on your wireless network to find out what MAC addresses are used by computers on your network, and a PC that allows its MAC address to be cloned so that it is identical to the MAC address of one your own wireless computers (which is possible with most PC wireless network adapters) even an amateur hacker can defeat MAC address filtering in minutes.
    By the way - I don't think your posted message here is off topic. In my opinion, the Airport discussion forums are the best place to post any questions related to usage of wireless networks. Questions of this nature are virtually never specific to any Mac model.

  • Newbie saving question in Illustrator

    I know this is a newbie question. I designed a logo in Illustrator. Is there a way to save just the logo for exporting into other applications (ie Pagemaker or Photoshop) without having the white artboard?
    Thanks
    Brad

    I don't know Pagemaker but with Photoshop I simply select all, copy and then paste in Photoshop - transparency will be maintained. If you paste as a Smart Object you retain the ability to edit the Illustrator artwork in Illustrator and update the PS file.

  • Java Socket Question

    Bonjour all,
    I have a bit of a weird question about Socket output and input streams, when I use the following code everything works fine.
    Socket soc = new Socket("123.456.789.1", 1234);
    +//     Send data request+
    +DataOutputStream dos = new DataOutputStream(soc.getOutputStream());
    dos.writeInt(INT);
    dos.flush();
    +//     Wait for reply+
    ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
    ArrayList<String> files = (ArrayList<String>) ois.readObject();
    How ever if I declare my Output and Input Stream readers together, my program justs hangs.
    Socket soc = new Socket("123.456.789.1", 1234);
    +//     Define streams+
    DataOutputStream dos = new DataOutputStream(soc.getOutputStream());
    ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
    +//     Send data request+
    dos.writeInt(INT);
    dos.flush();
    +//     Wait for reply+
    ArrayList<String> files = (ArrayList<String>) ois.readObject();
    Anyone got any ideas why this is??
    Edited by: 836869 on 15-Feb-2011 04:02

    You have to flush your ObjectOputStream first, it is worth noting that you are not, 1) using an ObjectOutputStream, 2) flushing it before opening the ObjectInputStream.
    Try this.
    ObjectOutputStream oos = new ObjectOutputStream(soc.getOutputStream());
    oos.flush();
    ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());If you want to swap an integer as part of the header, you can do the following.
    ObjectOutputStream oos = new ObjectOutputStream(soc.getOutputStream());
    oos.writeObject(INT);
    oos.flush();
    ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
    Integer intValue = (integer) ois.readObject();

  • Dumb newbie hardware question! :)

    Hi folks,
    I'm new to the world of the blackberry and am just about to take the plunge with an unlocked sim-free BB Bold to use in the UK on Vodafone. I have read about the software differences between BIS and BES and would be going for a BIS set-up. My dumb newbie question is does the hardware come in BES and BIS versions or not?
    Many thanks in advance and feel free to mock my foolishness
    Solved!
    Go to Solution.

    hello, about BIS and BES it's explained on the website but it's clear that if someone sums it up for you it will be easier...
    so BES is a type of contract between a company and Blackberry. The company IT buy computers, put Blackberry servers, and buy a fleet of Blackberry Devices for the people in the company to use them and get email through the Blackberry servers.
    BIS is a type of contract between a common person and a carrier. The consumer goes to the carrier, and buys a Blackberry device, and a BIS plan that will enable him/her to :
    phone/sms/mms
    receive emails that have been configured on the BIS site
    do data things if you subscribe to (like browse the web)
    You can buy a Blackberry from a carrier that has a deal with RIM (the company that sells Blackberries). Or you can buy a blackberry alone, and then go and contact a carrier that has a deal with RIM.
    phone/sms/mms
    receive emails that have been configured on the BIS site
    do data things if you subscribe to (like browse the web)
    The search box on top-right of this page is your true friend, and the public Knowledge Base too:

  • NEWBIE SOA Question:Appl Development for SOA

    This question may have been answered elsewhere; if so, my apologies.
    As a newbie to SOA, I am trying to wrap my head around the question of how app. development for SOA differs from traditional models. For example, non-SOA environments there are few external considerations when coding a process,
    but in SOA environments, I understand everything is a service.
    Can someone provide a few code snippets as to how they would look in each environment?
    I have read through several documents on SOA and have done the SOA tutorial, etc. but I have yet to see a side-by-side comparison of application code in SOA and non-SOA environments.
    How would an architect plan the translation and mapping of business objectives and functional requirements into a technical solution for SOA, architecting the SOA solution ?
    I would really appreciate any pointers (links to articles, etc.) in this direction. Thank you.
    Gordon

    Hello Gordon,
    SOA (Service Oriented Architecture) - as the name indicates, it's design is based on services. SOA is another integration technique which is used for small scale integration. SOA is an approach to have software resources in an enterprise available and discoverable on network as well defined services. Each service would achieve a predefined business objective and perform discrete units of work. The services are independent and do not depend on the context or state of the other services. They work within distributed systems architecture.
    Few links which may help you in understanding SOA and it's design patterns -
    http://blogs.oracle.com/jeffdavies/2008/10/architects_dictionary.html
    http://www.oracle.com/technology/tech/soa/mastering-soa-series/part1.html
    http://www.oracle.com/technology/tech/soa/mastering-soa-series/part2.html
    http://www.oracle.com/technology/tech/soa/mastering-soa-series/part3.html
    http://www.oracle.com/technology/tech/soa/mastering-soa-series/part4.html
    http://www.oracle.com/technologies/soa/docs/soa-bp-design-patterns-whitepaper.pdf
    http://www.oracle.com/technology/pub/articles/erl_soa_design_patterns_app_sequences.html
    http://www.oracle.com/technology/oramag/oracle/09-sep/o59architect.html
    http://www.oracle.com/technology/pub/articles/tech_arch.html#soa
    Regards,
    Anuj

  • Newb HD questions...?

    I'm a newb to HD and we've just got funding for a HD camera. The boss bought a Panasonic AG-HMC150P.
    The question is about recording mode, in "p" or "i". Currently it is set for 1080/60i, its top setting. But it has a 1080/30p too.
    Our products will be made to view on a TV screen ntsc, and a computer screen.
    Is the "i" setting the best for us? ie: is there any advantage in us using the 30p setting?
    Also, I have FCP6 and a colleague has FCP5 on a less powerful machine.
    Whats the best way to hand him newly captured HD footage? Is it to render it out using H264 on my machine before passing it over?
    We are hoping funding for software upgrade/machine will come soon for him.

    Well, the short answer is "i" (interlaced) is only for display on older CRT "tube" televisions. "p" (progressive) is for display on computers and flat screen televisions. Typically you should try to stay progressive these days. 60i can be useful if you are going to slow-mo any shoots.
    Do NOT convert your files to H.264 to send to another edit. H.264 is not a good codec for editing, use it for distribution of edited material only.
    For sharing with FCP5 on a slower computer, consider using DVCProHD.

  • Newbie audio question--help please...

    I recently recorded/captured video from Canon HV30 and unfortunately found that only Left audio channel was recorded..Right channel in non-existant. How do I duplicate the audio track from Left to Right so that both tracks are played in sync?
    I appreciate your help on this newbie question!

    When the left channel is filled you use the Fill Left effect
    The Fill Left effect duplicates the left channel information of the audio clip and places it in the right channel, discarding the original clip’s right channel information.
    Instead of putting the effect on each clip use the Audio Mixer.

  • Z97S Krait Edition CPU Socket Question

    Hi, I'm wondering whether the socket backplate on the reverse side of the the board is insulated. So far I have been unable to find any specific information online - although it seems that some ASUS products come with this as a protective feature. I'm just wondering whether this comes as a default for all socket 1150 boards. The reason I'm asking is because I am concerned that this item may come into contact with the chassis of my case and would like some peace of mind on this matter.
    I've attached a photo of the item in question - the silver socket behind the X shaped backplate (btw this is not a actual photo of my motherboard).
    Cheers

    the image isn't show up, you have to add tag in your post to show it
    ie:
     edit your post, then choose "Attachments and other options"
    then select desire placement/location in your reply and click on
    [Insert Attachment 1 in the message]
    [Insert Attachment 2 in the message]
    or use direct tags in your message to access the attached files with:
    Code: [Select]
    [_attachthumb=1]
    [_attachthumb=2]
    without "_" in front

Maybe you are looking for

  • Preview Mode shows different page than design mode

    When I am editing my page in Design mode in Muse CC, the page is approximately 700px long. When I preview that same page within Muse, it adds about 300px to the bottom of the page. There are no text boxes or other content that is causing the shift? W

  • ANNOUNCE: Ajax4jsf version 1.0.4 has been released

    Ajax4jsf is an open source extension to the JavaServer Faces standard that adds AJAX capability to JSF applications without requiring the writing of any JavaScript. Home Page: https://ajax4jsf.dev.java.net/ Download Page: https://ajax4jsf.dev.java.ne

  • How do I change the computer name of my iPhone?

    In Mac OS X, we can go to System Preferences / Sharing, and set our Computer Name. Is there something like this for the iPhone? I'd like to rename mine to something more customized (and identifiable) for when it displays on a home network.

  • Debug RFC called from external system with no dialog user

    Hi all, We need to debug the rfc function module which is called from the external system( Siebel ) . The user id is not dialog user so can not set external debugger. Need you help. Thanks, Anmol.

  • Run JMF in Forte

    Could anyone tell me how I can run JMF in Forte? Where can I add this JMF in Forte? ken