Passing primitives through sockets

I've just started with Java networking, and I have a few questions. Say I've sent a packet, and I know that the first two bytes in that packet combine to make an int. Is this the best way of sending and recieving the data, or is there an easier way?
Client:
public class ClientPrim {
     Socket socket;
     BufferedOutputStream out;
     public ClientPrim() {
          try {
               socket = new Socket("localhost", 9090);
               out = new BufferedOutputStream(socket.getOutputStream());
               int anInt = 30000;
               int anotherInt = 60000;
               byte[] bytes = new byte[4];
               bytes[0] = (byte) (anInt>>8);
               bytes[1] = (byte) (anInt&0xff);
               bytes[2] = (byte) (anotherInt>>8);
               bytes[3] = (byte) (anotherInt&0xff);
               out.write(bytes, 0, bytes.length);
               out.flush();
               out.close();
          } catch (Exception e) {
               e.printStackTrace();
     public static void main(String [] args) {
          ClientPrim c = new ClientPrim();
}Server:
public class ServPrim {
     private ServerSocket server;
     public ServPrim() {
          try {
               server = new ServerSocket(9090);
               while (true) {
                    Socket con = server.accept();
                    BufferedInputStream in = new BufferedInputStream(con.getInputStream());
                    byte[] bytes = new byte[4];
                    in.read(bytes, 0, bytes.length);
                    int firstBig = bytes[0]>=0?bytes[0]:bytes[0]+256;
                    int firstSmall = bytes[1]>=0?bytes[1]:bytes[1]+256;
                    int secondBig = bytes[2]>=0?bytes[2]:bytes[2]+256;
                    int secondSmall = bytes[3]>=0?bytes[3]:bytes[3]+256;
                    int firstInt = (firstBig<<8) + firstSmall;
                    int secondInt = (secondBig<<8) + secondSmall;
                    System.out.println(firstInt+" "+secondInt);
                    con.close();
          catch (IOException e) {
               e.printStackTrace();
     public static void main(String[] args) {
          ServPrim s = new ServPrim();
}With all the bit operations it seems very messy, surely theres an easier way? I've also managed to send the data via serialized wrapper classes, but will this have a large effect on the speed? I'd rather put in a bit of extra effort and have a fast program
Thanks

Take a look at java.io.DataOutputStream and java.io.DataInputStream. Nice toys like readInt() in there.
Careful with read(): if you try to read() four bytes you can get one, two, three, or four bytes. TCP/IP can split up and combine writes into packets any way it feels like. DataInputStream has readFully() which will loop doing read() until it gets the requested amount of data.
There is an idiom to do byte to unsigned byte conversion:
byte b;
int n = b & 0xff;

Similar Messages

  • Problem in passing byte through socket

    Hi to all,
    I'm trying to pass a byte[] through socket.
    The code where the data is sent is the following:
    byte[] data = new byte[len];
    // read the byte[] from another InputStream
    inStream.read(data, 0, len);
    // carry data to another OutputStream
    handler.out.println("$crypted_obj "+len+" "+pcol_step); //handler.out is a PrintWriter
    handler.incoming.getOutputStream().write(data);
    handler.incoming.getOutputStream().flush();I try to read in this way:
    byte[] data = new byte[len];
    is.read(data, 0, len);When the read is launched for the first time, it return only an array full of zeros, the other times return the right data array.
    I have tried to use BufferedInputStream and BufferedOutputStream but it's the same.
    In debugging mode(Eclipse) all work fine.
    Anyone have a suggestion for solve this problem?
    Thanks in Advice
    Manuel

    But why the sender don't write the bytes?Because the length is wrong, or you have a bug in your sending code which you haven't posted yet.
    Before of the byte[] data I sent a string through a PrintWriter that work on the same OutputStream. The string arrive correctly.Don't use two kinds of streams or Readers or Writers on the same stream. It doesn't work.
    os.write(data); //this is not sent!It is if you flush it.

  • Does my MacBook passes audio through Mini Display Port or not?

    I recently bought a Mini DisplayPort > HDMI adapter in order to display my MacBook on my TV. Other users of the same adapter publicly stated that they got video AND audio out, but I got only video.
    I've been searching this online for two days now and I still don't know why (I even searched this support forum, but I must admit that I got a little lost and decided to write my own topic). All I discovered was that some MacBooks have this capacity (to port audio along with video through Mini DisplayPort) and others don't.
    I'm using a white MacBook unibody bought new and latest on late 2009. It's the first model with multitouch trackpad and without FireWire port. Its model name is "MacBook 6,1", I guess.
    Does anybody know for sure if It CAN, in fact deliver audio+video through the Mini DisplayPort if I'm using a compatible HDMI adapter?
    Thanks.

    These models pass audio through the display port:
    iMac (Late 2009), MacBook Pro (Mid 2010), MacBook (Mid 2010), and Mac mini (Mid 2010) supply multichannel audio (up to 8 channels) and video signals over Mini DisplayPort. To connect your television or other HDMI devices to your Mac, use select third-party Mini DisplayPort to HDMI adapters that conform to the VESA v1.1a DisplayPort Interoperability Guidelines. The following adapters adhere to these standards:
    - Moshi Mini DP to HDMI Adapter with Audio Support
    - Griffin Video Display Converter (Mini DisplayPort to HDMI and DVI)

  • Pass parameter through standard page "import xml content and actions"

    Dear Portal experts,
    As you know, a standard portal page is configured to allow the import of XML file. It is located in the portal in the path system admin -> transport -> xml content and actions -> import
    I configured a quick link u201Cimportu201D to the page so now the link http://myserver:port/irj/portal/import allows me to access directly to this screen.
    What I would like to do now is to pass the parameter related to u201Cfile nameu201D through this screen meaning that I would like that http://myserver:port/irj/portal/ import/filename=C:\test.xml  fills automatically the fields u201CXML fileu201D with  C:\test.xml 
    Please do you know how to achieve this ?
    Thank you very much and regards

    hi,
    @Maksim :
    When user launch an URL like http://myserver:port/irj/portal/ import/*filename=C:\test.xml, he is requested to provide username and password; as this link is a shortcut for the upload xml page, there is a check of authorization and only portal admin that have authorization and permission on this page/iview will be able to upload xml file through the URL. Hope this clarify.
    @Kumar :
    thank you for your answer. What a pity to not be able to pass parameter through standard portal page/iview particularly knowing that we can pass paramater through many kinds of iviews (transactional iview, url iview, VC iview...). I explored some option on file com.sap.portal.ivs.init.par but this was unsuccessful. However, thanks to this [link bellow|http://wiki.sdn.sap.com/wiki/display/Snippets/ComponenttouploadXMLfilewithPCD+objects], I was able to upload through URL the XML file.
    The problem is that I can upload only XML file that are stored in the server not in the local user computer. My requirement is to be able to upload local XML file stored on user's computer.
    If someone could provide and idea/solution, I would be very grateful.
    Cheers

  • Can't connect to local MySQL server through socket '/var/mysql/mysql.sock'

    I'm using the pre-installed versions of php and mysql under Mac OS X Server 10.4.4 running on a G4 and am unable to get anything involving mysql to work.
    I ssh to the server and enter various commands in Terminal:
    on typing "mysql" I get
    ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (2)
    and on typing "mysqladmin version" I get
    mysqladmin: connect to server at 'localhost' failed
    error: 'Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (2)'
    Check that mysqld is running and that the socket: '/var/mysql/mysql.sock' exists!
    On typing "sudo mysqld_safe" I get
    Starting mysqld daemon with databases from /var/mysql
    STOPPING server from pid file /var/mysql/MyServer.local.pid
    070722 16:06:05 mysqld ended
    /var/mysql/MyServer.local.err contains
    070722 16:06:04 mysqld started
    070722 16:06:04 [Warning] Setting lowercase_tablenames=2 because file system for /var/mysql/ is case insensitive
    070722 16:06:04 InnoDB: Database was not shut down normally!
    InnoDB: Starting crash recovery.
    InnoDB: Reading tablespace information from the .ibd files...
    InnoDB: Restoring possible half-written data pages from the doublewrite
    InnoDB: buffer...
    070722 16:06:05 InnoDB: Starting log scan based on checkpoint at
    InnoDB: log sequence number 0 43634.
    /var/mysql has permissions 775.
    The line
    mysql.default_socket = /var/mysql/mysql.sock
    is in /etc/php.ini
    whereis mysqladmin ->
    /usr/bin/mysqladmin
    whereis mysql ->
    /usr/bin/mysql
    ls /var/mysql ->
    MyServer.local.err
    ib_logfile1
    mysql
    ib_logfile0
    ibdata1
    test
    Can't find my.cnf or my.ini anywhere
    Can't find mysql.sock anywhere
    I'm trying to get a bug database running (mantis) under Mac OS X Server 10.4.4 that I can access from local clients.
    I'm trying to follow directions at http://www.mantisbugtracker.com/manual/manual.installation.php
    without knowing anything about mysql or php and I'm stuck on step 3:
    "Next we will create the necessary database tables and a basic configuration
    file."
    I get a message saying
    "Does administrative user have access to the database? ( Lost connection to MySQL server during query )"
    I don't even know if following the mantis directions has resulted in the creation of a database or not. Where would it be?
    Thanks for any help.
    Intel iMac   Mac OS X (10.4.10)  

    I've just done a clean install of OSX Server and added the latest MYSQL packaged installer. Afterwards I found the lock file in /private/tmp/mysql.lock
    The easiest way to solve this problem is to create a symbolic link so that the lock file appears to be in right place.
    e.g.
    cd /var
    sudo mkdir mysql <== this assumes the directory is missing
    cd mysql
    sudo ln -s /private/tmp/mysql.sock mysql.sock
    After this msql commands should work fine, and you've not fiddled with the security settings on users/groups.
    HTH
    Christian

  • "Can't connect to local MySQL server through socket '/tmp/mysql.sock'"

    Data Services=3.1
    Repository=12.2.2.0000
    Red Hat Enterprise 5
    Designer,Job Server,Job Engine=12.2.2.3
    After an unscheduled server reboot with DS up and running when trying to start a job in either Data Services Management Console or DS Designer getting the following:
    "Can't connect to local MySQL server through socket '/tmp/mysql.sock'"
    The mysql.sock have never been in /tmp and on the production server it does not exist there and the production server is up and running correctly. If a link is created to mysql.sock(/home/user/boedge31/bobje/mysql) the job will start but return this message: 
    "Cannot retrieve <Version> from the repository. Additional database information: <SQL submitted to ODBC data source <localrepo> resulted in error <MySQL ODBC 3.51 Driver mysqld-5.0.46-enterprise No database selected>. The SQL submitted is <select VERSION, SECURITYKEY, GUID from AL_VERSION where NAME = 'Repository Version'"
    I checked and AL_VERSION and the Version field exist. 
    Before the shut down DS was working correctly and had no issues.  My best guess is a part of the repository was corrupted during the unscheduled shut down.  It seems like DS has "forgotten" some of the settings.  
    Any suggestions on a possible solution?

    The issue has been solved. 
    There was a bad path in $LD_LIBRARY_PATH.
    Removed the path and DS started working again.

  • Logging through sockets

    Hi
    I'm trying to send logging information through sockets using log4j.
    My configuration file is :
    log4j.rootLogger=Debug, Socket
    log4j.appender.Socket=org.apache.log4j.net.SocketAppender
    log4j.appender.Socket.Port=12345
    log4j.appender.Socket.RemoteHost=localhost
    log4j.appender.Socket.LocationInfo=true
    the server only reads the input string that the logger sends.
    I'm getting this exception on the client side:
    log4j:WARN Detected problem with connection: java.net.SocketException: Software caused connection abort: socket write error
    and this message on the server:
    Server started...
    Client accepted
    ������������org.apache.log4j.spi.LoggingEven�������������

    Ryan,
    I think if I could log to something common like Microsoft Access it would be a help to me in managing database backups and other things, as Citadel is somewhat unique in its format and methods using the Measurement and Automation Explorer. Maybe I could retrieve data from a 3rd party database back into Citadel if Citadel DB becomes corrupted or lost.
    I don't use ODBC logging now, so please excuse me if I come across as lacking in understanding your request. Could the hypertrend or other objects be programmed to log and/or retrieve data to and/or from the 3rd party ODBC database as well?
    Terry Parks, Engineering Analyst
    Terrebonne Parish Consolidated Government (T.P.C.G.)
    Public Works - Pollution Control

  • Is it possible to pass parameters through eventlisteners?

    Hello everyone!
    Inside a .fla file I have some buttons and each button will tween a different image to the stage. All the images are outside the stage in the same x and y position and I just need to tween the x coordinate.
    Now I'm working with an external document class where I'm trying to hold all my functions and I'm stucked with the Tweens. I'm willing to stay away from the flash tween engine and I'm trying to work with tweenLite.
    My question is: Is it possible to pass parameters through eventListeners so I can use something like this inside my docClass?
         public function animeThis (e:MouseEvent, mc:MovieClip, ep:int):void { //ep stands for endPoint.
         TweenLite.to(mc, 2, {x:ep});
    If this is possible, how am I supposed to write the listeners so it will pass the event to be listened for AND those parameters? And how to build the function so it will receive those parameters and the event?
    If this is not possible, what's the best approach to do this?
    Thanks again!

    So, I understand you need to match buttons with corresponding visuals.
    Here is a suggested approach.
    Since SimpleButton is not a dynamic class, I suggest you have an enhanced base class for these buttons that extends SimpleButton. What is enhanced is that button has reference to the target.
    I wrote code off the top of my head and it may be buggy. But concept is clear:
    This is base class for all the buttons:
    package 
         import flash.display.DisplayObject;
         import flash.display.SimpleButton;
         public class NavButton extends SimpleButton
              public var targetObject:DisplayObject
              public function NavButton()
    Now, this is your doc class that utilizes this new buttons:
    package 
         import flash.display.DisplayObject;
         import flash.display.MovieClip;
         import flash.display.Sprite;
         import flash.events.Event;
         import flash.events.MouseEvent;
         public class DocClass extends Sprite
              private var btnArray:Array;
              private var visuals:Array;
              // references to objects being swapped
              private var visualIn:MovieClip;
              private var visualOut:MovieClip;
              public function DocClass()
                   if (stage) init();
                   else addEventListener(Event.ADDED_TO_STAGE, init);
              private function init(e:Event = null):void
                   removeEventListener(Event.ADDED_TO_STAGE, init);
                   // buttons and MCs shouldn't be in the same array - otherwise it is counterintuitive
                   // assuming all the objects are on stage
                   btnArray = [price_btn, pack_btn, brand_btn, position_btn];
                   visuals = [g19_mc, g16_mc, g09_mc, g04_mc];
                   configObjects();
              private function configObjects():void
                   var currentVisual:MovieClip;
                   var currentButton:NavButton;
                   for (var i:int = 0; i < btnArray.length; i++)
                        currentVisual = visuals[i];
                        // hold original positioin
                        currentVisual.hiddenPosition = currentVisual.x;
                        currentButton = btnArray[i];
                        // set target MC
                        currentButton.targetObject = currentVisual;
                        currentVisual.addEventListener(MouseEvent.CLICK, placeObject);
                        currentButton.addEventListener(MouseEvent.CLICK, placeObject);
              private function placeObject(e:MouseEvent):void
                   // if NavButton is clicked - make new visual targeted for moving in and currently visible object subject for moving out
                   if (e.currentTarget is NavButton) {
                        visualOut = visualIn;
                        visualIn = NavButton(e.currentTarget).targetObject;
                   else {
                        // otherwise - move visual out
                        visualOut = visualIn;
                   swapVisuals();
               * Accompishes visuals swapping
              private function swapVisuals():void {
                   if (visualIn) TweenLite.to(visualIn, .3, { x:0 } );
                   if (visualOut) TweenLite.to(visualOut, .3, { x:visualOut.hiddenPosition } );

  • "secured by passing data through LWAPP tunnels."

    Hi,
    The WLC v4.1 Config Guide says,
    "all Layer 2 wired communications between
    controllers and lightweight access points are secured by passing data through LWAPP tunnels."
    Is it correct that this is only true for the LWAPP Control channel which is encrypted - the LWAPP Data channel is in clear text which WireShark has no problem parsing, right?
    Regards, MH

    Only LWAPP control message payloads are encrypted. As you've stated however LWAPP data payaloads are not encrypted as the wired network is assumed to be relatively secure (compared to wireless).
    Additional Reference Appendix B in this document:
    http://www.cisco.com/en/US/netsol/ns340/ns394/ns348/networking_solutions_white_paper0900aecd805e0862.shtml

  • Transfering a file through Socket programming

    Hi all,
    I want to return a file from server to client through a socket. I tried using ObjectOutput Stream where in I returned a java.io.File from server. But at client side when I say file.getLeangth() it comes as 0 and if I try to assign FileInputStream on the object it throws an exception as the file not found as the path associated with the file will be of Server.
    So can anyone help as to how to transfer a file through socket programming???
    thx in advance
    MK

    java.io.File is NOT the contents of the file. It really just represents the path.
    If you want to transfer the file's contents, you'll have to use a FileInputStream or FileReader, read from it, and then write the bytes or chars on the wire.

  • Data are not transfered as unicode through sockets

    I have aplication with connection through sockets. I use PrintWriter and BufferedReader for writing and reading data, created lik this:
    pw = new PrintWriter( skt.getOutputStream(), true );
    br = new BufferedReader( new InputStreamReader( skt.getInputStream() ) );
    When I send data I put this code for checking:
    int tmpSize = str.length();
    for( int i = 0; i < tmpSize; i++ )
         char chr = str.charAt( i );
         int tmpInt = (int)chr;
         System.out.print( tmpInt + " " );
    System.out.println();
    pw.println( str );
    And when I receive data I put something similar with string read with
    br.readLine().
    For unicode characters the result is different ( I use ascii and russian characters ). At sending data, it is normal, and at receiving I get '?' instead of unicode characters, something like this
    109 101 115 115 58 98 108 117 101 58 32 1092 1099
    before sending data and this
    109 101 115 115 58 98 108 117 101 58 32 63 63
    after receiving.
    Can somebody help me with this, or it is a bug?

    Ok, I just solved it. I had to create reader and writer like this:
    pw = new PrintWriter( new OutputStreamWriter( skt.getOutputStream(), "UTF-16" ) );
    br = new BufferedReader( new InputStreamReader( skt.getInputStream(), "UTF-16" ) );
    Seems that default encoding set was not unicode even if it is Writer and Reader!

  • Connecting to localhost through socket

    Hi Friends
    I want to connect to the localhost (wamp server) and need to read the video file byte by byte through socket please help me to find out the solution.
    Thanks
    Sam

    Turn off your Firewall
    wamp use generally the port 80
    Can you tell more about your problem?

  • MySQL can't connect through socket error

    I have been mucking around with MySQL and have broken something.
    Running 10.4.3 server, I get a "Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (2)" error
    Was working fine before I decided to mess with things - I think I altered the hostname from localhost to 192.168.x.x etc.
    Now I cannot connect, and MySQL manager won't start it. I would like to make it work again rather than have to install a different version.
    When MySQL manager installs the requisite files for the first time, where does it store these, and how can I do this again?
    Thanks
    Hamish

    There's an issue with authentication between PHP 5 and MySQL 4.1
    This thread should contain a resolution for you.
    http://discussions.apple.com/thread.jspa?messageID=665175&#665175
    FYI- A search here for "MySQL PHP socket" reveals the above thread and other threads with the same issue.
    Jeff

  • How to pass arraylist through URL ?

    Hi,
    Can we pass arraylist through URL using params.put ?
    If so then how to access each value?..because pageContext.getParameter with return string...
    Any other method can we use ?
    Thanks

    You should store in on the session or transaction depending on the scope.

  • File thansfer through socket problem

    i am writing server /client program, where the server wait for client request to send or receive file through socket.
    can i use 1 socket to handle the request (client want to send or download file) and file data transfer?
    if yes, how to handle the beginging of file transfer after receive a request?
    and how can server know when the file transfer is completed?

    This tutorial should help:
    http://java.sun.com/docs/books/tutorial/networking/index.html

Maybe you are looking for

  • Problem with SDO_ADMIN.update_index procedure

    Hi all: We use for develpment Oracle 10g XE utilizing Oracle Spatial (SDO) in relational model , with this version works great, all procedures work with out problems. Recently we want try Oracle 11g, i create the schema, relational model, the same th

  • BW Objects storage location

    Hi All, I would like to know where extactly the objects created in BW (like ODS, CUBE, Info Objects,..) will store, means these tables will belongs to which part of the Database, how to know the location of these tables in the database. Regards, Geet

  • Sp.js Is not loading in Application pages

    Unable to get property 'get_current' of undefined or null reference  is getting while running application page. <asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server"> <SharePoint:ScriptLink ID="ScriptLink2" Na

  • Entity validation behavior in multi-step process

    I'm using jdev 11g with ADF BC and I want to create a multi-step process with a train to split a long form into multiple views. The fields on the form are based on a entity object that was created from a database table. Most of the fields are mandato

  • File types spontaneously changed.

    Recenty, I moved some AIFF files from my laptop to an external hard drive, to free up some space temporarily for a project. When I moved the files back, they had been changed from AIFF files to "Source Files" and "Unix Executable Files". I have a fee