Read byte from a long

Hi,
How can I read bytes from a long. i..e read one byte by one byte from long.
Naman Patel

ok here is my problem how do i ignore the sign byte i.e please check this code
long nr=1345345333L, add=7, nr2=0x12345671L;
          long tmp;
          long[] result = new long[2];
          char[] pwd = password.toCharArray();
          for (int pCount = 0; pCount < pwd.length; pCount++){
               if (pwd[pCount] == ' ' || pwd[pCount] == '\t')
                    continue;
               tmp= (long) pwd[pCount];
               nr^= (((nr & 63)+add)*tmp)+ (nr << 8);
               nr2+=(nr2 << 8) ^ nr;
               add+=tmp;
          result[0]=nr & (((long) 1L << 31) -1L); /* Don't use sign bit (str2int) */;
          result[1]=nr2 & (((long) 1L << 31) -1L);
          int i = 0;
          long x = result[0];
          byte b[] = longToBytes(x);
          String str = "";
          i = 0;
          while(i < 4){
               if(b[i] == 0x00) {
                    System.out.println("byte is 0x00");
                    str += "00";
               else {
                    if(b[i] <= 0x0f && b[i] >= 0) {
                         System.out.println("byte is 0x0f" + b);
                         str += "0";
                    break;
               i++;
          i = 0;
          str += Long.toHexString(result[0]);
          x = result[1];
          b = longToBytes(x);
          while(i < 4){
               if(b[i] == 0x00) {
                    System.out.println("byte is 0x00");
                    str += "00";
               else {
                    if(b[i] <= 0x0f && b[i] >= 0) {
                         System.out.println("byte is 0x0f");
                         str += "0";
                    break;
               i++;
          str += Long.toHexString(result[1]);

Similar Messages

  • Reading bytes from CLOB not BLOB

    I know that DBMS_LOB.SUBSTR can read number of bytes (for BLOBs) or characters (for CLOBs).
    What I want is to read bytes from BLOB instead of characters.
    The following tries to read 4000 bytes. Unfortunately It fails to read 4000 bytes if size of CLOB_COLUMN is bigger than 4000 bytes.
    select dbms_lob.substr(utl_raw.cast_to_raw(CLOB_COLUMN),4000,1) from dualIs it possible to get only these 4000 bytes from CLOB_COLUMN?
    Thank you in advance.

    Welcome to the forum.
    Unfortunately It fails to read 4000 bytes if size of CLOB_COLUMN is bigger than 4000 bytes.Could it be you're mixing up things?
    DBMS_LOB.SUBSTR reads bytes from BLOBS, characters from CLOBS.
    "amount Number of bytes (for BLOBs) or characters (for CLOBs) to be read."
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_lob.htm#sthref3199
    No need to cast_to_raw, afaik:
    SQL> create table t as select to_clob(lpad('*', 10000, '*')) clob_col from dual;
    Table created.
    SQL> desc t;
    Name                                                                   Null?    Type
    CLOB_COL                                                                        CLOB
    SQL> select substr(clob_col,1, 4000) substr
      2  ,      length(substr(clob_col,1, 4000)) substr_lngth
      3  ,      dbms_lob.substr(clob_col, 4000, 1) lob_substr
      4  ,      length(dbms_lob.substr(clob_col, 4000, 1)) lob_substr_length
      5  from t;
    SUBSTR                                                                           SUBSTR_LNGTH
    LOB_SUBSTR
    LOB_SUBSTR_LENGTH
    ********************************************************************************         4000
                 4000
    1 row selected.

  • Failed to read bytes from InputStream

    Hi,
    I get this excpetion log when I try to read a stream from weblogic. Can anyone help me out why this happens and what
    could be done to overcome this
    ####<Aug 8, 2007 4:48:37 PM EDT> <Error> <HTTP> <sundev01> <fhsserver> <[ACTIVE] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1186606117277> <BEA-101019> <[weblogic.servlet.internal.WebAppServletContext@111f9b - name: 'FFMS', context-path: '/FFMS'] Servlet failed with IOException
    java.io.IOException: failed to read '2678' bytes from InputStream; clen: 58512 remaining: 44902 count: 1394
    at weblogic.servlet.internal.ChunkOutput.writeStream(ChunkOutput.java:411)
    at weblogic.servlet.internal.ChunkOutputWrapper.writeStream(ChunkOutputWrapper.java:168)
    at weblogic.servlet.internal.ServletOutputStreamImpl.writeStream(ServletOutputStreamImpl.java:496)
    at weblogic.servlet.internal.ServletOutputStreamImpl.writeStream(ServletOutputStreamImpl.java:484)
    at weblogic.servlet.FileServlet.sendFile(FileServlet.java:400)
    at weblogic.servlet.FileServlet.doGetHeadPost(FileServlet.java:224)
    at weblogic.servlet.FileServlet.service(FileServlet.java:166)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:225)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:127)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:272)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:165)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3150)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:1973)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:1880)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1310)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:207)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:179)
    >

    Hi Aravind,
    Which version of weblogic are u using?
    Cheers,
    Lakshmi

  • Reading bytes from a server

    Ok,
    I want to connect to a server and recieve a data from it.
    the data is broken up as follows:
    int flag;
    int x, y;
    String name;
    the server i'm communicating with is written in C, so i'm trying to figure out how i'm going to recieve this data.
    What is the size that java uses to store an integer value?
    IF java uses unicode, that's two bytes per character right?
    so if name was 30 characters long it would be 60 bytes?
    i'm thinking of trying to either read the whole transmission into one string then separate, or separate as it comes in?
    could someone suggest how to proceed>

    Java holds (primitive) integers in 32 bits.
    Java holds characters in 16 bits (two bytes)
    30 characters will occupy 30*16 = 480 bits (60 bytes)
    Java provides the java.net package for networking. In there you can find a class called Socket that identifies the clients's communication endpoint, and encapsulates a host and an application address (port).
    First you open a socket to a server:
    Socket s = new Socket( serverName, serverPort );
    then you just read an input stream from the socket.
    DataInputStream dis = new DataInputStream( s.getInputStream() );
    String message = dis.readUTF(); //wait for server to send
    s.close() // close the socket
    Now, you can do with message whatever you like. It's that simple!
    For more information you can see the related tutorials from java.

  • How can I read bytes from std input using nextByte()

    Hi. I am trying to read input text from std input into a byte array. I used the following procedure but have been getting errors
    Scanner myScanner = new Scanner(System.in);
         do{
              List[i] = myScanner.nextByte();
              i++;
         }while(i<List.length);
    When i try to print the List array after this loop, i get an InputMismatchException and Unknown Source error. What could be responsible for this?
    Thanks

    i don't really know what you're trying to do, but try this:
    maybe it helps you out.
    byte List[] = new byte[10];
            for (int i = 0; i < List.length; i++) {
                Scanner myScanner = new Scanner(System.in);
                List[i] = myScanner.nextByte();
            }this code creates an array of byte elements. the length of the array is 10 ( = new byte[*10*]). the for loop let's you fill the array with byte numbers over the keyboard.
    good luck

  • Hi, I am using USB 8476s to communicat​e to a slave unit in LIN network using LabVIEW7.1​. Can anyone tell me how i can send a header file plus 1 byte of data to the slave in a LIN network. or how do i use ldf file. i want to read responses from the slave

    Hi,   I am using USB 8476s to communicate to a slave unit in LIN network. Can anyone tell me how i can send a header frame plus 1 byte of data to the slave in a LIN network. or how do I communictae with slave using LabVIEW7.1.
    I want to read responses from the slave. When i tried with labview exapmle programs or even using MAX also, while doing some switching action in my slave, i am getting response as Device inactive with timestamp but there is no data format. 
    And I have Lin Description File. Can you suggest me how to use ldf file.
    I am at customer place and It would be great help from you if you can suggest me at the earliest. Thank you

    you may use the LDF Starter Kit to use LDF informations in your application
    http://joule.ni.com/nidu/cds/view/p/id/665/lang/en

  • Error 105, Could not read full block (2048 bytes) from checkpoint file ~/dirchk/sdfsdj.cpe

    Hi expert,
        i am getting below error in goldengate  due to mount point full and i released the space and still the same error for all gg processes. i can see the *cpe cpr file become 0 bytes. so i deleted and re added the extract and repliacat and while adding the replcat i used add replicat  checkpoint table because of that multiple entries of same replicat came in checkpoint table . my checkpoint details also  present in ./GLOBALS. now my doubt is if add  replicate with mentioning checkpoint table name  will duplicate entry will be created or what is the work around for this.
    MANAGER RUNNING
    Invalid checkpoint for EXTRACT  qqqq   (error 105, Could not read full block (2048 bytes) from checkpoint file XXXXXXXXX)
    Invalid checkpoint for EXTRACT  qqq(error 105, Could not read full block (2048 bytes) from checkpoint file XXXXXXXXXX)
    Invalid checkpoint for REPLICAT qqq  (error 105, Could not read full block (2048 bytes) from checkpoint file XXXXXXXXXXX)

    Hi Kariyath
    Increase the page size of your windows machine.Check for the recommanded page size.Remember that the recommanded page size should be the lower limit.If you have any issue feel free to ask.Your prob will be solved
    Award suitable points

  • IPad no longer reads PDFs from iWeb site like it did in mid April offering to read PDF in iBooks.

    iPad no longer reads PDFs from iWeb site like it did in mid April offering to read PDF in iBooks.

    How to Transfer Everything from an Old iPad to New iPad
    http://osxdaily.com/2012/03/16/transfer-old-ipad-to-new-ipad/
    iOS: Transferring information from your current iPhone, iPad, or iPod touch to a new device
    http://support.apple.com/kb/HT2109
    Moving Content to a New iPad
    http://tinyurl.com/qzk2a26
    How to Transfer App Data and Game Saves from One iOS Device to Another
    http://lifehacker.com/5891964/can-i-transfer-app-data-and-game-saves-from-my-iph one-to-a-new-ipad
    How to transfer data from your old iPad to your new iPad
    http://www.imore.com/how-transfer-data-your-old-ipad-your-new-ipad-air-or-retina -ipad-mini
    Transferring your prepaid cellular data account depends on your carrier. AT&T lets you move it yourself when you go to Cellular Data in Settings and log into your account with your previous AT&T user name and password. For iPads with Sprint service, you can set up an account on the new iPad and contact Sprint Customer Care (888-211-4727 and go through the menus) to deactivate the old plan and get credit for unused service. For Verizon, call the company’s customer service number for mobile broadband support (800-786-8419) and ask to have your account transferred.
     Cheers, Tom

  • How to read a byte[] from a file

    Hi can someone help me to read a byte[] from a file. I need to save a byte[] to a file and then retrieve it later can someone help in this..
    Thanx

    there are actually docs on the classes ByteArrayInputStream and ByteArrayOutputStream here:
    http://java.sun.com/javase/6/docs/api/
    go there (copy & paste in browser) and text search for the above classes.
    Then read into it. That way, you will come to a better comprehension of the entire thing. You may as well want to read this:
    http://java.sun.com/docs/books/tutorial/essential/io/index.html
    And for the future: if you have general problems, search API docs and tutorials first and solve them yourself. The guys around here can get pretty annoyed about "Teach me the entire Java Thing" (also called "someone do my homework") requests.
    If you have a special problem, ie an Exception you don?t understand or a method wich you don?t know how it works, everybody will like to help you.
    Only few real serial killers frequent these forums.

  • How can we read some bytes from every line of the file

    How can we read some bytes from the every line of the file moving on to the next line
    without using the read line

    Actualiy readLine() takes more execution time
    for reading a part of line if we can do so without
    readLine() we can save some time...Well, if you knew, beforehand, the length of each line, you could use RandomAccessFile and its seek method, but, since you don't, you would have to read the rest of the line character-by-character, checking to see if it is a newline, in order to place the "cursor" at the beginning of the next line in order to read the next few characters you want.
    So, as you can see, you will need to read the entire line anyway (and if you do it yourself you also have to do the checking yourself considering all three possible end-of-line sequences), so you just as well use readLine().
    Some people may suggest Scanner and it's nextLine() method, but that also needs to read the rest of line (as evidenced by the fact that it returns it), so that is no different than the readLine() (or read it yourself) solution.

  • How to read bytes(image) from a server ?how to display image after read byt

    How to read bytes(image) from a server ?how to display image after reading bytes?
    i have tried coding tis , but i couldnt get the image to be display:
    BufferedInputStream in1=new BufferedInputStream(kkSocket.getInputStream());
    int length1;
    byte [] data=new byte[1048576];
    if((length1=in1.read(data))!=-1){
    System.out.println("???");
    }System.out.println("length "+length1);
    Integer inter=new Integer(length1);
    byte d=inter.byteValue();

    didn't I tell you about using javax.imageio.ImageIO.read(InputStream) in another thread?

  • SocketInputStream.read(byte[], int, int) extremely slow

    Hi everyone,
    I'm trying to send several commands to a server and for each command read one or more lines as response. To do that I'm using a good old Socket connection. I'm reading the response lines with BufferedReader.readLine, but it's very slow. VisualVM says, that SocketInputStream.read(byte[], int, int) is consuming most of the cpu time. A perl script, which does the same job, finishes in no time. So it's not a problem with the server.
    I'm runnning java version "1.6.0_12"
    Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
    Java HotSpot(TM) Server VM (build 11.2-b01, mixed mode) on Linux henni 2.6.25-gentoo-r7 #3 SMP PREEMPT Sat Jul 26 19:35:54 CEST 2008 i686 Intel(R) Core(TM)2 Duo CPU E6550 @ 2.33GHz GenuineIntel GNU/Linux and here's my code
    private List<Response> readResponse() throws IOException {
            List<Response> responses = new ArrayList<Response>();
            String line = "";
            while ( (line = in.readLine()) != null) {
                int code = -1;
                try {
                    code = Integer.parseInt(line.substring(0, 3));
                    line = line.substring(4);
                } catch (Exception e) {
                    code = -1;
                // TODO create different response objects ?!?
                NotImplemented res = new NotImplemented(code, line);
                responses.add(res);
                // we received an "end of response" line and can stop reading from the socket
                if(code >= 200 && code < 300) {
                    break;
            return responses;
        }Any hints are appreciated.
    Best regards,
    Henrik

    Though it's almost an sscce I posted there, I will try to shrink it a little bit:
    Dummy server:
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class Server {
        public Server() throws IOException {
            ServerSocket ss = new ServerSocket(2011);
            Socket sock = ss.accept();
            BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            PrintStream ps = new PrintStream(sock.getOutputStream());
            ps.println("200 Welcome on the dummy server");
            String line = "";
            while(line != null) {
                line = br.readLine();
                ps.println("200 Ready.");
        public static void main(String[] args) throws IOException {
            new Server();
    }the client:
    import java.io.IOException;
    import java.io.PrintStream;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.Scanner;
    import de.berlios.vch.Config;
    public class Client {
        private Socket socket;
        private PrintStream out;
        private Scanner scanner;
        public Client(String host, int port, int timeout, String encoding)
            throws UnknownHostException, IOException {
            socket = new Socket();
            InetSocketAddress sa = new InetSocketAddress(host, port);
            socket.connect(sa, timeout);
            out = new PrintStream(socket.getOutputStream(), true, encoding);
            scanner = new Scanner(socket.getInputStream(), encoding);
        public synchronized void send(String cmd) throws IOException {
            // send command to server
            out.println(cmd);
            // read response lines
            readResponse();
        public void readResponse() throws IOException {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
                int code = -1;
                try {
                    code = Integer.parseInt(line.substring(0, 3));
                    line = line.substring(4);
                } catch (Exception e) {
                    code = -1;
                if (code >= 200 && code < 300) {
                    break;
        public static void main(String[] args) {
            try {
                Client con = new Client("localhost", 2011, 500, "utf-8");
                con.readResponse();
                con.send("version 0.1");
                con.send("menu = new menu Feeds");
                con.send("menu.EnableEvent close");
                con.send("menu.SetColorKeyText -red 'Öffnen'");
                for (int i = 0; i < 100; i++) {
                    String groupId = "group"+i;
                    long start = System.currentTimeMillis();
                    con.send(groupId+" = menu.AddNew OsdItem '"+groupId+"'");
                    con.send(groupId+".EnableEvent keyOk keyRed");
                    long stop = System.currentTimeMillis();
                    System.out.println((stop-start)+"ms");
            } catch (Exception e) {
                e.printStackTrace();
    }This code makes me believe, it's not a java problem, but some system setting of my os.

  • When using the Database Connectivity Toolset, reads and writes with long binary fields are incompatible.

    I am trying to write LabVIEW Variants to long binary fields in a .mdb file using the Database Connectivity Toolset. I get errors when trying to convert the field back to a variant after reading it back from the database.
    I next tried flattening the variant before writing it and ultimately wound up doing the following experiments:
    1) If I use DB Tools Insert Data to write an ordinary string and read it back using a DB Tools Select Data, the string is converted from ASCII to Unicode.
    2) If I use DB Tools Create Parameterized Query to do an INSERT INTO or an UPDATE operation, specifying that the data is BINARY, then read it back using a DB Tools Select Data,
    the length of the string is prepended to the string itself as a big-endian four-byte integer.
    I can't think of any way to do a parameterized read, although the mechanism exists to return data via parameters.
    Presuming that this same problem affects Variants when they are written to the database and read back, I could see why I get an error. At least with flattened strings I have the option of discarding the length bytes from the beginning of the string.
    Am I missing something here?

    David,
    You've missed the point. When a data item is flattened to a string, the first four bytes of the string are expected to be the total length of the string in big-endian binary format. What is happening here is that preceding this four-byte length code is another copy of the same four bytes. If an ordinary string, "abcdefg" is used in place of the flattened data item, it will come back as <00><00><00><07>abcdefg. Here I've used to represent a byte in hexadecimal notation. This problem has nothing to do with flattening and unflattening data items. It has only to do with the data channel consisting of writing to and reading from the database.
    I am attaching three files that you can use to demonstrate the problem. The VI file c
    ontains an explanation of the problem and instructions for installing and operating the demonstration.
    Ron Martin
    Attachments:
    TestLongBinaryFields.vi ‏132 KB
    Sample.UDL ‏1 KB
    Sample.mdb ‏120 KB

  • A better way to Read Bytes until Done ?

    My question involves reading an unknown number of bytes from the serial
    port. One method is to just wait a defined amount of time to receive
    the bytes and hope you caught all of them. Better: count them until
    they are all received. I have attached an image which shows the method
    I use to count bytes until all bytes are received. However, this method
    is rather slow. It's taking me 500mS to read data that I can normally
    read in 230mS. Is the shift register making this loop slow? Is there a
    better way to read the bytes until all bytes are in?
    Richard
    Attachments:
    ReadBytes.gif ‏5 KB

    Thanks for your reply Chilly.
    Actually, you are correct on both accounts, the delay and the wire from
    the output of Write, and in fact, I usually do those things. I was just
    in a hurry to get an example posted and didn't have my real data.
    To put my issue in broader prospective, I have attached an image that shows boh methods I've used to count bytes. One
    shows the method I use to count bytes until all bytes are received. The
    other is a "hard wired" timer method that I try to avoid, but at least
    it is fast. Notice the text in red. Why would I be able to read the
    byes so much faster in the "hard wired" version? It has to be either
    the shift register, the AND, or the compare functions, and I still
    can't beleive these things would be slower than the Express timer
    function in the other method.
    Methodology: The 235mS timer used in the "hard wired" method was
    emperically derived. The 150 bytes are received 100% of the time when
    235mS is allowed. 230mS yields about 90% of the bytes, the it goes down
    exponentially. I found that the shift register method method trakes
    ~515mS avg by putting a tick count on both sides of the loop and
    finding the resulting time. I also did that with the hard wired method
    and found it to be dead on 235mS which at least proves the Express vi
    works very well
    Message Edited by Broken Arrow on 09-05-2005 08:31 PM
    Message Edited by Broken Arrow on 09-05-2005 08:32 PM
    Richard
    Attachments:
    CoutingBytes.GIF ‏25 KB

  • TcpListener not working on Azure: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host

    Hi Everybody,
    i'm playing a little bit with Windows Azure and I'm blocked with a really simple issue (or maybe not).
    I've created a Cloud Service containing one simple Worker Role. I've configured an EndPoint in the WorkerRole configuration, which allows Input connections via tcp on port 10100.
    Here the ServiceDefinition.csdef file content:
    <?xml version="1.0" encoding="utf-8"?>
    <ServiceDefinition name="EmacCloudService" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition" schemaVersion="2014-01.2.3">
    <WorkerRole name="TcpListenerWorkerRole" vmsize="Small">
    <Imports>
    <Import moduleName="Diagnostics" />
    <Import moduleName="RemoteAccess" />
    <Import moduleName="RemoteForwarder" />
    </Imports>
    <Endpoints>
    <InputEndpoint name="Endpoint1" protocol="tcp" port="10100" />
    </Endpoints>
    </WorkerRole>
    </ServiceDefinition>
    This WorkerRole is just creating a TcpListener object listening to the configured port (using the RoleEnvironment instance) and waits for an incoming connection. It receives a message and returns a hardcoded message (see code snippet below).
    namespace TcpListenerWorkerRole
    using System;
    using System.Net;
    using Microsoft.WindowsAzure.ServiceRuntime;
    using System.Net.Sockets;
    using System.Text;
    using Roche.Emac.Infrastructure;
    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.WindowsAzure.Diagnostics;
    using System.Linq;
    public class WorkerRole : RoleEntryPoint
    public override void Run()
    // This is a sample worker implementation. Replace with your logic.
    LoggingProvider.Logger.Info("TcpListenerWorkerRole entry point called");
    TcpListener listener = null;
    try
    listener = new TcpListener(RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Endpoint1"].IPEndpoint);
    listener.ExclusiveAddressUse = false;
    listener.Start();
    LoggingProvider.Logger.Info(string.Format("TcpListener started at '{0}:{1}'", RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Endpoint1"].IPEndpoint.Address, RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Endpoint1"].IPEndpoint.Port));
    catch (SocketException ex)
    LoggingProvider.Logger.Exception("Unexpected exception while creating the TcpListener", ex);
    return;
    while (true)
    Task.Run(async () =>
    TcpClient client = await listener.AcceptTcpClientAsync();
    LoggingProvider.Logger.Info(string.Format("Client connected. Address='{0}'", client.Client.RemoteEndPoint.ToString()));
    NetworkStream networkStream = client.GetStream();
    StreamReader reader = new StreamReader(networkStream);
    StreamWriter writer = new StreamWriter(networkStream);
    writer.AutoFlush = true;
    string input = string.Empty;
    while (true)
    try
    char[] receivedChars = new char[client.ReceiveBufferSize];
    LoggingProvider.Logger.Info("Buffer size: " + client.ReceiveBufferSize);
    int readedChars = reader.Read(receivedChars, 0, client.ReceiveBufferSize);
    char[] validChars = new char[readedChars];
    Array.ConstrainedCopy(receivedChars, 0, validChars, 0, readedChars);
    input = new string(validChars);
    LoggingProvider.Logger.Info("This is what the host sent to you: " + input+". Readed chars=" + readedChars);
    try
    string orderResultFormat = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes("\xB")) + @"MSH|^~\&|Instrument|Laboratory|LIS|LIS Facility|20120427123212+0100||ORL^O34^ORL_O34| 11|P|2.5.1||||||UNICODE UTF-8|||LAB-28^IHE" + Environment.NewLine + "MSA|AA|10" + Environment.NewLine + @"PID|||patientId||""""||19700101|M" + Environment.NewLine + "SPM|1|sampleId&ROCHE||ORH^^HL70487|||||||P^^HL70369" + Environment.NewLine + "SAC|||sampleId" + Environment.NewLine + "ORC|OK|orderId|||SC||||20120427123212" + Encoding.ASCII.GetString(Encoding.ASCII.GetBytes("\x1c\x0d"));
    writer.Write(orderResultFormat);
    catch (Exception e)
    LoggingProvider.Logger.Exception("Unexpected exception while writting the response", e);
    client.Close();
    break;
    catch (Exception ex)
    LoggingProvider.Logger.Exception("Unexpected exception while Reading the request", ex);
    client.Close();
    break;
    }).Wait();
    public override bool OnStart()
    // Set the maximum number of concurrent connections
    ServicePointManager.DefaultConnectionLimit = 12;
    DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString");
    RoleEnvironment.Changing += RoleEnvironment_Changing;
    return base.OnStart();
    private void RoleEnvironment_Changing(object sender, RoleEnvironmentChangingEventArgs e)
    // If a configuration setting is changing
    LoggingProvider.Logger.Info("RoleEnvironment is changing....");
    if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))
    // Set e.Cancel to true to restart this role instance
    e.Cancel = true;
    As you can see, nothing special is being done. I've used the RoleEnvironment.CurrentRoleInstance.InstanceEndpoints to retrieve the current IPEndpoint.
    Running the Cloud Service in the Windows Azure Compute Emulator everything works fine, but when I deploy it in Azure, then I receive the following Exception:
    2014-08-06 14:55:23,816 [Role Start Thread] INFO EMAC Log - TcpListenerWorkerRole entry point called
    2014-08-06 14:55:24,145 [Role Start Thread] INFO EMAC Log - TcpListener started at '100.74.10.55:10100'
    2014-08-06 15:06:19,375 [9] INFO EMAC Log - Client connected. Address='196.3.50.254:51934'
    2014-08-06 15:06:19,375 [9] INFO EMAC Log - Buffer size: 65536
    2014-08-06 15:06:45,491 [9] FATAL EMAC Log - Unexpected exception while Reading the request
    System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
    at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
    --- End of inner exception stack trace ---
    at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
    at System.IO.StreamReader.ReadBuffer(Char[] userBuffer, Int32 userOffset, Int32 desiredChars, Boolean& readToUserBuffer)
    at System.IO.StreamReader.Read(Char[] buffer, Int32 index, Int32 count)
    at TcpListenerWorkerRole.WorkerRole.<>c__DisplayClass0.<<Run>b__2>d__0.MoveNext() in C:\Work\Own projects\EMAC\AzureCloudEmac\TcpListenerWorkerRole\WorkerRole.cs:line 60
    I've already tried to configure an internal port in the ServiceDefinition.csdef file, but I get the same exception there.
    As you can see, the client can connect to the service (the log shows the message: Client connected with the address) but when it tries to read the bytes from the stream, it throws the exception.
    For me it seems like Azure is preventing the retrieval of the message. I've tried to disable the Firewall in the VM in Azure and the same continues happening.
    I'm using Windows Azure SDK 2.3
    Any help will be very very welcome!
    Thanks in advance!
    Javier
    En caso de que la respuesta te sirva, porfavor, márcala como válida
    Muchas gracias y suerte!
    Javier Jiménez Roda
    Blog: http://jimenezroda.wordpress.com

    hi Javier,
    I changed your code like this:
    private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false);
    public override void Run()
    TcpListener listener = null;
    try
    listener = new TcpListener(
    RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Endpoint"].IPEndpoint);
    listener.ExclusiveAddressUse = false;
    listener.Start();
    catch (SocketException se)
    return;
    while (true)
    IAsyncResult result = listener.BeginAcceptTcpClient(HandleAsyncConnection, listener);
    connectionWaitHandle.WaitOne();
    The HandleAsync method is your "While (true)" code:
    private void HandleAsyncConnection(IAsyncResult result)
    TcpListener listener = (TcpListener)result.AsyncState;
    TcpClient client = listener.EndAcceptTcpClient(result);
    connectionWaitHandle.Set();
    NetworkStream netStream = client.GetStream();
    StreamReader reader = new StreamReader(netStream);
    StreamWriter writer = new StreamWriter(netStream);
    writer.AutoFlush = true;
    string input = string.Empty;
    try
    char[] receivedChars = new char[client.ReceiveBufferSize];
    // LoggingProvider.Logger.Info("Buffer size: " + client.ReceiveBufferSize);
    int readedChars = reader.Read(receivedChars, 0, client.ReceiveBufferSize);
    char[] validChars = new char[readedChars];
    Array.ConstrainedCopy(receivedChars, 0, validChars, 0, readedChars);
    input = new string(validChars);
    // LoggingProvider.Logger.Info("This is what the host sent to you: " + input + ". Readed chars=" + readedChars);
    try
    string orderResultFormat = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes("\xB")) + @"MSH|^~\&|Instrument|Laboratory|LIS|LIS Facility|20120427123212+0100||ORL^O34^ORL_O34| 11|P|2.5.1||||||UNICODE UTF-8|||LAB-28^IHE" + Environment.NewLine + "MSA|AA|10" + Environment.NewLine + @"PID|||patientId||""""||19700101|M" + Environment.NewLine + "SPM|1|sampleId&ROCHE||ORH^^HL70487|||||||P^^HL70369" + Environment.NewLine + "SAC|||sampleId" + Environment.NewLine + "ORC|OK|orderId|||SC||||20120427123212" + Encoding.ASCII.GetString(Encoding.ASCII.GetBytes("\x1c\x0d"));
    writer.Write(orderResultFormat);
    catch (Exception e)
    // LoggingProvider.Logger.Exception("Unexpected exception while writting the response", e);
    client.Close();
    catch (Exception ex)
    //LoggingProvider.Logger.Exception("Unexpected exception while Reading the request", ex);
    client.Close();
    Please try it. For this error message, I suggest you could refer to this thread (http://stackoverflow.com/questions/6173763/using-windows-azure-to-use-as-a-tcp-server
    ) and this post (http://stackoverflow.com/a/5420788).
    Regards,
    Will
    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.

Maybe you are looking for

  • Warning Message in query result as 'Notification Number DBMAN 345'

    Hi , I have a warning message while executing the query 'Diagnosis Currently, it cannot be guaranteed that SIDs and master data exists for all characteristic attributes for the DataStore object to be read. There is a restriction on a navigation attri

  • Satellite PRO A200-1S1 with Windows 7 x32. Touchpad doesn't work

    Hi everybody I Installed Windows 7 on my Satellite Pro A200-1S1, retrieved all the drivers on Toshiba site, everything works fine (less than the web camera that didn't work even with previous s.o. XP or Vista...). But my Touchpad doesn't work at all.

  • How to add page to parent page

    I created a page and forgot to chose HOme page as parent, how can I now set Home page as PARENT page to this page. SENKS

  • Who Updated the Memo field

    I am trying to determine if it is possible to find out who updated a column field like the function ColumnHistory() shows the history.  I would like to see which user made the changes in the ColumnHistory().  Is it possible to do this?

  • Icloud pop up won't accept my appleid password

    The icloud pop up keeps showing up and won't accept my my appleid, even after I've changed it and have rebooted the ipad numerous times!!! I'm almost to the point of smashing this thing into pieces.