TCP/IP servidor

Buen día,
Construí un servidor que envía datos de tamaño 8,7 y 6 Bytes; y tengo un cliente que recibe tramas de 8 Bytes solamente (No puedo cambiar el tamaño del buffer del cliente). Como puedo lograr que mi servidor envié siempre tramas de 8 Bytes, esto es por que en algunos momentos mis datos tiene valores inferiores al valor que mi cliente recibe, lo cual provoca un error en los datos recibidos.
Muchas gracias..Saludos cordiales
Adjunto imagen del servidor TCP
Solved!
Go to Solution.
Attachments:
Server_TCP_labview.png ‏25 KB

Que tal ivan_1982;
Una manera sencilla de hacer lo que quieres sería rellenar los Bytes faltantes con un espacio, para hacerlo puedes utilizar un código como el que te muestro a continuación.
Si después de leer el número utilizas una función Fractional String to Number no deberían de darte problema los espacios, pero si necesitas quitárselos puedes utilizar la siguiente función
Espero que la información te sea de ayuda
Suerte
Francisco Arellano
National Instruments Mexico
Field Systems Engineer - Energy Segment
www.ni.com/soporte

Similar Messages

  • Retroalimentacion usando TCP/IP

    Hola, estoy trabajando en un proyecto para controlar los motores de un robot, al principio utilice la comunicacion Cliente /Servidor usando los ejemplos de TCP/IP de LV, enviando datos desde el servidor hasta el cliente donde tengo una tarjeta DAQ 6009 que envía las señales correspondientes para el control del motor, la DAQ es capaz de leer dos encoders al mismo tiempo que manda las señales al motor, y ahora quiero que los datos recibidos por estos encoders sean enviados al servidor para que me sirvan como un control retroalimentado, el problema es que no he podido hacer esto, me he basado en los ejemplos de LV 8.5, pero no he podido hacer que el servidor reciba y menos que utilice los datos detectados por la daq que esta en el cliente, aqui tengo los vi's en el que me estoy basando y que no funciona, por favor si alguien puede decirme como hacer que mi sistema reciba y envie datos al mismo tiempo, o alguna otra solución, se lo agredeceré mucho.
    Attachments:
    Emisor-servver1.vi ‏25 KB
    Receptor-client1.vi ‏24 KB

    Hola Lunazuly
    Primero antes de interactuar con DAQ te sugiero que hagas primero la parte de la comunicación. Muy probablemente tienes un problema de sincronía entre el Cliente/Servidor.
    Antes de continuar con TCP/IP, me gustaría saber si no te conviene más utilizar variables compartidas para la comunicación?, te voy a enviar un tutorial para que lo evalúes, pero sería una alternativa bastante sencilla.
    De manera contraria, házmelo saber y revisamos en que puedes estar teniendo el problema.
    Saludos
    Coamín Cruz
    AE México

  • Como comunico un plc s7 400h siemens con labview si utiliza industrial ethernet tcp/ip

    hola a todos
    Necesito comunicar con labview un plc s7 400h  de siemens, utiliza industrial ethernet tcp/ip  me gustarìas saber de que forma lo puedo comunicar, si es necesario utilizar algùn opc o si solamente con los vi's de tcp puedo comunicarlos

    Hola elias 2231, para comunicarte con un PLC a través de Labview básicamente tienes 3 opciones I/O digital, estándares de red, y OPC.
    Utilizar las salidas digitales de tu PLC, y conectaras a una tarjeta DAQ, o a un PAC.
    Para la parte de estándares de red como mencionas tcp/ip, puedes generar una arquitectura cliente servidor, y enviar los datos por tcp/ip, para implementar el cliente o servidor en labview puedes encontrar un ejemplo en find examples.
    Finalmente, y muchas veces la opción mas sencilla es el uso de un OPC Server, para conectarte con este las dos opciones principales son utilizar el modulo de DSC (data and supervisor y control) que es la mas sencilla o por medio de Datasocket en el cual realizarías una conexión a cada elemento de tu OPC
    Por facilidad y para reducir el tiempo de desarrollo yo te recomendaría utilizar el modulo de DSC
    Los siguientes links pueden ser de interés
    http://sine.ni.com/nips/cds/view/p/lang/en/nid/2342
    http://digital.ni.com/public.nsf/websearch/F92C1F2F7B35105B86256DB200628B24
    Saludos
    Benjamin C
    Senior Systems Engineer // CLA // CLED // CTD

  • TCP Listen.vi " trabado "

    Hola, saludos a quien lea este tema.
    La situacion es, tengo un cliente y un servidor, el servidor siempre esta esperando que el cliente se active y el TCP listen.vi en el servidor se active con un tiempo infinito de espera, sin embargo esto no ocurre despues de algunos dias de estar funcionando correctamente. No marca ningun error simplemente no responde a las peticiones del cliente. 
    La pregunta es: ¿Por que deja de funcionar el TCP listen.vi del servidor y si es posible que exista alguna degradacion de este?
    Nota: Cabe señalar que existe comunicacion entre el cliente y servidor, esto fue probado con un "PING"obteniendo respuesta y aun asi el tcp listen deja de funcionar o de reconocer que el cliente le esta escribiendo.

    Hola Jonathan no debería de
    haber motivo para que se interrumpa la conexión o se degrade la señal, aquí
    puede manejar esto dependiendo de la arquitectura de tu programa. Las desconexiones
    en red se pueden dar por muchos motivos, por lo que seria bueno agregues algo
    para que pueda volver a establecer conexión. Con respecto al lis tener, a lo
    mejor el sistema operativo o el antivirus lo bloquea por la actividad o algo
    mas trato de conectarse.
    Aquí lo que puedes hacer es
    colocar un timeout grande y si se da, simplemente que regrese al mismo estado y
    vuelves abrir la conexión con esto la puedes mantener fresca.
    Saludos
    Benjamin C
    Senior Systems Engineer // CLA // CLED // CTD

  • Resetear conexion TCP IP

    Buenas,
    Necesito ayuda sobre como poder resetear una conexión TCP-IP.
    El problema lo tengo, cada vez que se me desactiva el cRIO desde la fuente de alimentación, al reiniciar el sistema se queda colgado al intentar volver a conectar. (ya que mi servidor no detecta que el dispositivo se ha desconectado)
    He estado mirando y en la paleta de TCP_Ip sólo viene la opcion de cerrar la conexión, pero al reiniciar el sistema no puedo hacerlo así, ya que no tengo el ID.
    Me podeis por favor ayudar o indicar como se puede solucionar esto?
    Un saludo y muchas gracias.

    Here's one suggestion:
    1. Create a Client class.
    2. Create a Server class.
    3. Create a SpawnedServer class.
    4. Create an Application or whatever that uses the Client class.
    1. The Client class has as a data member a Socket that connects to the server and gets the info.
    2. The Server class has a ServerSocket and also has a while true loop that does the following:
    Socket sock = servSock.accept()
    new SpawnedServer(sock).start()
    3. The SpawnedServer class has a Socket data member that gets initialized in its constructor that is
    called when it is created above. The SpawnedServer class extends Thread and does most of its work
    in the run method.
    4. Start the server.
    5. Run application programs as desired.
    Think of all of the things that you would want a Client to do:
    For example, open a connection, receive a message, close a connection, output the reply...
    Think of all of the things that you would want a SpawnedServer to do:
    receive a message, process a message, respond to a message...
    Implement a small portion. Test it. When it works, implement another and test it. Do this until completed.
    I hope this advice helps some. I am relatively new to the programming game, but have found that it is very helpful
    to implement piece by piece when a program is somewhat complex.
    Good luck.

  • Utilização de dois servidores PI

    Boa Tarde a todos,
    Na empresa que estou trabalhando, já existia um servidor PI 7.0 para sistemas legados e no projeto de implementação do GRC NFe, a consultoria optou por efetuar a instalação em um outro servidor PI dedicado para o GRC.
    Por política da empresa, os servidores serão migrados de datacenter, e surgiu uma dúvida na preparação dessa migração. Já verifiquei em outros posts, ser possível a instalação em somente 1 servidor, mas a pergunta é:
    Existe uma "recomendação" formal da SAP para que sejam utilizados 2 servidores?
    Abraços
    Migdon

    Sao duas discussoes:
    1. usar o PI corporativo ou um PI exclusivo pra NFE:
    O ponto aqui é o impacto de negocio. Interfaces de NFE, caso falhem, impedem a empresa de faturar. Em muitas empresas, o PI é um sistema nao estabilizado ainda com diversos erros de interface ao longo do tempo, e devido às filas das msgs assincronas, se parar uma interface, para "tudo". Tendo PIs separados, vc evita q problemas de interfaces menos prioritarias impactem em processos mais criticos como NFE; provavelmente foi essa a visao da sua consultoria. Claro que isso tem um lado negativo, que é aumentar a complexidade do seu landscape, aumentando o custo de manutencao.
    2. Instalar os 3 componentes (SLL-NFE, SLL-NFE-JWS e XI Content) em uma unica instancia ou usar instancias separadas.
    Existe uma recomendacao formal de nao se instalar outro aplicativo junto com o PI (verifique isso no master guide do Netweaver). Mas isso nao tem nada a ver com NFE, eh uma recomendacao padrao devido ao alto consumo de recursos pelo PI.
    Claro que se a empresa faz um sizing capaz de suportar a demanda de recursos, nada impede tecnicamente de instalar tudo junto.
    Note que sao 2 pontos distintos.
    Mesmo usando 1 PI pra NFE separado do PI corporativo, vc pode ainda ter tudo nessa mesma instancia de PI NFE ou instalar os componentes ABAP e Java em outras instancias, assim como se vc usa o PI corporativo tb pra NFE, vc poderia tb instalar os componentes ABAP e Java juntos ou em outra instancia.
    Abs,
    Henrique.

  • No puedo conectar iCloud desde Windows vista, me marca error de servidor. Que hago para poder acceder iCloud desde vista?

    No puedo conectar iCloud desde Windows vista, me marca error de servidor. Que hago para poder acceder iCloud desde vista?

    The neighbor discovery on mac and PCs is based on broadcast.
    I think it's the same for yoru SQL application.
    Broadcast are blocked by default on the controller. You can enable "broadcast forwarding" in the controller menu

  • ITunes is unable to connect the server " iTunes não conecta com o servidor"

    Microsoft Windows 7 x64 Ultimate Edition Service Pack 1 (Build 7601)
    Sony Corporation VPCEH30EB
    iTunes 10.6.1.7
    O QuickTime não está disponível
    FairPlay 1.14.37
    Apple Application Support 2.1.7
    Biblioteca do Atualizador do iPod 10.0d2
    CD Driver 2.2.0.1
    CD Driver DLL 2.1.1.1
    Dispositivo Móvel Apple 5.1.1.4
    Driver do Dispositivo Móvel da Apple 1.59.0.0
    Bonjour 3.0.0.10 (333.10)
    Gracenote SDK 1.9.5.502
    Gracenote MusicID 1.9.5.115
    Gracenote Submit 1.9.5.143
    Gracenote DSP 1.9.5.45
    Número de Série do iTunes 0036AE440EF3BFB0
    O usuário atual é um administrador.
    A data e a hora do local atual é 2012-05-31 15:55:20.
    O iTunes não está sendo executado no modo de segurança.
    A composição acelerada do WebKit está ativada.
    HDCP é compatível.
    Core Media é compatível.
    Informações da Exibição de Vídeo
    Intel Corporation, Intel(R) HD Graphics Family
    **** Informações de Plug-ins Externos ****
    Não há nenhum plug-in externo instalado.
    iPodService 10.6.1.7 (x64) está atualmente sendo executado.
    iTunesHelper 10.6.1.7 está atualmente sendo executado.
    Apple Mobile Device service 3.3.0.0 está atualmente sendo executado.
    **** Testes de Conectividade de Rede ****
    Informações do Adaptador de Rede
    Nome do Adaptador:              {50AABBFE-3154-4EAF-B85E-17BDFE017E80}
    Descrição:             Atheros AR9285 Wireless Network Adapter
    Endereço IP:          0.0.0.0
    Máscara da Sub-rede:           0.0.0.0
    Gateway Padrão:   0.0.0.0
    DHCP Ativado:       Sim
    Servidor DHCP:    
    Cessão Obtida:      Wed Dec 31 22:00:00 1969
    A Cessão Expira:   Wed Dec 31 22:00:00 1969
    Servidores DNS:   
    Nome do Adaptador:              {D179EF93-23E1-45F1-82FF-967B61C46D00}
    Descrição:             Realtek PCIe GBE Family Controller
    Endereço IP:          192.168.254.115
    Máscara da Sub-rede:           255.255.255.0
    Gateway Padrão:   192.168.254.90
    DHCP Ativado:       Não
    Servidor DHCP:    
    Cessão Obtida:      Wed Dec 31 22:00:00 1969
    A Cessão Expira:   Wed Dec 31 22:00:00 1969
    Servidores DNS:    192.168.254.90
    Nome do Adaptador:              {8CE4C975-44D1-40F6-B07A-F91A95955EF9}
    Descrição:             Microsoft Virtual WiFi Miniport Adapter
    Endereço IP:          0.0.0.0
    Máscara da Sub-rede:           0.0.0.0
    Gateway Padrão:   0.0.0.0
    DHCP Ativado:       Sim
    Servidor DHCP:    
    Cessão Obtida:      Wed Dec 31 22:00:00 1969
    A Cessão Expira:   Wed Dec 31 22:00:00 1969
    Servidores DNS:   
    Conexão Ativa:      Conexão de rede local
    Conectado:             Sim
    On-line:                  Sim
    Usando Modem:     Não
    Usando LAN:          Sim
    Usando Proxy:       Não
    Informações do Firewall
    O Firewall do Windows está inativo.
    A tentativa de conexão ao site da Apple falhou.
    Esgotou-se o tempo de conexão de rede.
    A conexão básica com a loja falhou.
    Esgotou-se o tempo de conexão de rede.
    A tentativa de conexão com o servidor da Gracenote foi bem-sucedida.
    Esgotou-se o tempo de conexão de rede.
    O iTunes nunca teve acesso à iTunes Store com êxito.

    Close your iTunes,
    Go to command Prompt -
    (Win 7/Vista) - START/ALL PROGRAMS/ACCESSORIES, right mouse click "Command Prompt", choose "Run as Administrator".
    (Win XP SP2 & above) - START/ALL PROGRAMS/ACCESSORIES/Command Prompt
    In the "Command Prompt" screen, type in
    netsh winsock reset
    Hit "ENTER" key
    Restart your computer.
    If you do get a prompt after restart windows to remap LSP, just click NO.
    Now launch your iTunes, Sync and see if it is working now.
    If you are still having these type of problems after trying the winsock reset, refer to this article to identify which software in your system is inserting LSP:
    iTunes 10.5 for Windows: May see performance issues and blank iTunes Store
    http://support.apple.com/kb/TS4123?viewlocale=en_US

  • Risco de Instalação do GRC no servidor do ECC

    Boa tarde,
    Estamos enfrentando uma situação no projeto onde temos o sistema L1U dividido em 3 clientes: 100, 200 e 300.
    Gostaria de saber sobre os risco e impactos da instalação da solução SAP GRC em um client do proprio ECC (no caso o 300), ao inves de utilizarmos um servidor a parte especifico, para suporte da solucao.
    Permaneço no aguardo.
    Atenciosamente

    O risco é o mesmo inerente à instalacao de 2 aplicacoes diferentes em uma mesma instancia: governanca do landscape.
    Imagine que a proxima versao do GRC venha sobre o netweaver 7.02 (nao sei se vai mudar, estou apenas supondo para demonstrar). O ERP 6.0 é baseado sobre o 7.00. Daí vc vai ter q aplicar o EhP do netweaver na instancia por causa do GRC, mas sem saber os impactos disso pro ERP. E outras coisitas mais...
    Enfim, nao eh recomendado, mas possivel.
    Abs,
    Henrique.

  • Servidores SEFAZ e SCAN ativos simultaneamente

    Henrique/Fernando,
    Na thread Contingencia SCAN automatizado? o Henrique mencionou que:
    1) Pra cada nota que ele vai numerar, o ERP "pergunta" ao GRC qual sistema está ativo no momento, e baseado nesta informação ele escolhe qual form utilizar para numerar.
    2) Se ambos estao fora, a nota nao é numerada, fica parada no monitor, e daí vc pode optar por ativar a contingencia em formulario de seguranca ("central contingency", aquelas views que tem no menu da J1BNFE), e fazer o switch dessa pra contingencia.
    Abs,
    Henrique.
    Eu entendí que no casos dos dois servidores estarem inativos, podemos optar pela contingência no formulário, mas reparei que o ECC também valida os casos em que os servidores SCAN e SEFAZ estão ativos simultaneamente, não numerando a Notas nestes casos também.
    Caso isso ocorra, que ação o usuário deveria tomar? Ou trata-se de algum erro de configuração?
    Obrigada,
    Daniela

    Daniela,
    no codigo atual da RFC /XNFE/RFC_SRVSTA_READ, é impossível vc ter uma resposta ativa pros 2, devido ao seguinte trecho:
    * If SCAN and SEFAZ is active SEFAZ has priotity so only
    * sefazactive = X is sent to ERP. Scanactive is set to blank.
      LOOP AT et_status INTO es_status.
        IF es_status-sefazactive = 'X'.
          CLEAR es_status-scanactive.
          MODIFY et_status FROM es_status.
        ENDIF.
      ENDLOOP.
    Se vc nao tem esse codigo na sua versao, sugiro atualizar asap seu sistema.
    Abs,
    Henrique.

  • Error 'Program not registered' while testing RFC - SRM to MDM / TCP/IP conn

    Hello All,
    While testing RFC connection in SRM, we are getting this error. This connection between SRM to MDM. Any inputs will be highly appreciated.
    Error Details LOCATION: SAP-Gateway on host <hostname> / sapgw<instance no>
    our server OS : windows 2008 server
    We are getting error while doing connection test in SRM.
    This is sm59 connection (TCP/IP ) connection.
    Connection Type: T / RFC destination Name: MDM_API_CATALOG
    Registered server program: hostname.MDS
    I checked smgw transaction ..Logged on clients...Program id is not showing. Any hint will be helpful.
    I Checked this MDM setup also.
    MDS setup
    In mdm server go to folder F:\usr\sap\DM1\MDS00\config
    Open MDM.ini file in notepad
    Add the below 2 entries.
    SAP RFC Gateways= GWHOST=XXXX.hostnamexxx.xxx GWSERV=sapgw00
    Trusted SAP Systems= XXD
    This will enable gateway connection between SRM and MDM and will enable trusted connection.
    For trusted connections to work, we created a service user called SRM_MDM_API with SAP_ALL in SRM  and also created the same user in MDM with Default role.
    Error message:
    Logon  Connection Error
    Error Details    Error when opening an RFC connection
    Error Details    ERROR: program XXXXXXXXPRD.MDS not registered
    Error Details    LOCATION: SAP-Gateway on host XXXXXXXXprd.xx.xxxxxxhostname.xxx / sapgw00
    Error Details    DETAIL: TP XXXXXXXXPRD.MDS not registered
    Error Details    COMPONENT: SAP-Gateway
    Error Details    COUNTER: 77326
    Error Details    MODULE: gwr3cpic.c
    Error Details    LINE: 1778
    Error Details    RETURN CODE: 679
    Error Details    SUBRC: 0
    Error Details    RELEASE: 700
    Error Details    TIME:
    Error Details    VERSION: 2
    Procedure Tried
    1)  This procedure is for Linux OS - Similarly we tried in Windows OS ( If any procedure is wrong also, Please correct us)
    To register the program login into the OS level as sudo su u2013 <sid>adm and execute the following command.
    rfcexec u2013g<program id> -a<gateway host name> -x<gateway service>
    rfcexec is the server program name, the <program id> can be obtained from SM59, it is case sensitive and should match with the entry in SM59. The <gateway host name> and <gateway service> can be obtained from the transaction SMGW. When this command is executed it goes to a hanging loop.
    The connection will fail once this command is terminated or the user executing this command logs off
    2)
    To avoid this, instead of using the above mentioned command an entry should be made in the file saprfc.ini
    To do this, execute the following command
    sudo su u2013 <sid>adm
    rfcexec u2013D<destination name>
    <destination name> is the RFC destination name in SM59
    In order to do above step 2,  we could not find saprfc.ini in windows 2008 server. Please let us know path where it will be usually?
    3) Already checked the notes sapnote_0000684841
    I know that it is generic error..This is happening to specific one of system only.
    Thanks
    Edited by: saptest2011 on May 20, 2011 5:36 PM

    Hello SM,
    Thanks for your quick reply.
    Thanks for sharing link for document ie Configure the MDM Administration_cockpit. It is helpful. I read that document.
    But still issue remain there.
    The same RFC connection works between SRM sandbox to MDM sandbox.
    Only issue with SRM Prod to MDM Prod (newly built system)
    difference between MDM Prod and MDM sandbox.
    MDM Prod runs: Windows server 2008 OS
    MDM Sandbox runs: Windows server 2003 OS
    Landscape: PI7.1, MDM 7.1 and SRM 5.5, SRM-MDM Catalog 3.0
    Even i did os01 tcode ping test using host name (specific IP address) from SRM prod to MDM prod, it is fine.
    Thanks a lot for your help.
    I checked these notes also
    Note 353597 - Registering a server program
    Note 44844 - No connection to registered RFC program
    Note: in smgw tcode in SRM system, the required program id is not showing in logged on clients
    Thanks
    Edited by: saptest2011 on May 23, 2011 5:00 PM
    Edited by: saptest2011 on May 23, 2011 5:39 PM

  • XModem via TCP for Java

    I am sure that many of you experienced developers have read requests in the past concerning implmentation of Ward Christenen's XModem protocol over a TCP socket. If not, well... you are about to...
    This is a major hack... but it is starting to come together... thanks to Fred Potter for his source code to start this project...
    Objective:
    Basically, I want to create a console application which accepts an incoming connection and starts the receive mode for a XModem file transfer. I am using CGTerm (for Commodore retrocomputing) but can test with HyperTerminal as well...
    The user who connects to the server selects SEND and the FILE to send for a XModem file transfer... and the transfer begins...
    The incoming blocks of 128 bytes are written to a file
    After the transfer is over the server disconnects the client terminal.
    Here is what I have so far:
    import java.net.*;
    import java.lang.*;
    import java.io.*;
    // X-Modem Server implementation via TCP/IP socket
    public class XServer {
    public static FileWriter fw;
    public static void main(String[] args) throws IOException {
    // define the file
    try {   
    fw = new FileWriter("filename.txt");
    } catch (Exception e) {
    System.out.println(e);
    System.exit(0);
    int port = Integer.parseInt(args[0]);
    ServerSocket server = new ServerSocket(port);
    System.out.println("X-Server v1.0 - waiting for connection");
    Socket client = server.accept();
    // Handle a connection and exit.
    try {
    InputStream inputStream = client.getInputStream();
    OutputStream outputStream = client.getOutputStream();
    new PrintStream(outputStream).println("Go to send file mode!"); // sent to client
    System.out.println("Ready to receive file via X-Modem...");
    * BEGIN TRANSFER HERE!
    // set the debug flag
    XModem.debug = true;
    * Here we are instantiating a new InputStream that represents the remote
    * file that we are receiving. In this single line we are attempting to
    * start the flow.
    * Behind The Scenes: We're sending a NAK across the serial line repeatedly
    * until we finaly start seeing the data flow. If we don't see the data
    * flow, then we throw an exception.
    System.out.println("Sending NAK to start receive mode...");
    InputStream incomingFile;
    try {
    incomingFile = new XModemRXStream(inputStream, outputStream);
    } catch (IOException e) {
    System.out.println("ERROR! Unable to start file transfer!");
    e.printStackTrace();
    return;
    System.out.println("Starting file transfer...");
    * Here we are reading from the incoming file, byte by byte, and printing out.
    * Behind The Scenes: Internally, the read() method is handling the task of
    * asking for the next data block from the remote computer, processing it (i.e.
    * parsing, running checksums), and then putting it in an internal buffer. Not
    * all calls to read() will request a new data block as each block contains at
    * least 128 bytes of data. Sometimes you will only hit the buffer.
    try {
    for (;;) {
    int c = incomingFile.read();
    if (c==-1)
    break; // End of File
    // print character / byte
    System.out.print(c+",");
    // write to file
    try {       
    //System.out.print(".");
    fw.write(c);
    } catch (Exception e) {
    System.out.println(e);
    System.exit(0);
    } catch (IOException e) {
    System.out.println("error while reading the incoming file.");
    e.printStackTrace();
    return;
    // done
    System.out.println("File sent.");
    new PrintStream(outputStream).println("");
    new PrintStream(outputStream).println("transfer successful!");
    } finally {
    //client.close();
    // save the file
    try {   
    fw.close();
    System.out.println("file saved.");
    } catch (Exception e) {
    System.out.println(e);
    System.exit(0);
    * XModem keeps track of settings that the Receive and Transmit Stream classes will
    * reference.
    * <p>Copyright: Copyright (c) 2004</p>
    * @author Fred Potter
    * @version 0.1
    class XModem {
    public static boolean debug = false;
    * XModemRXStream is an easy to use class for receiving files via the XModem protocol.
    * @author Fred Potter
    * @version 0.1
    class XModemRXStream
    extends InputStream {
    // CONSTANTS
    private static final int SOH = 0x01;
    private static final int EOT = 0x04;
    private static final int ACK = 0x06;
    private static final int NAK = 0x15;
    private static final int CAN = 0x18;
    private static final int CR = 0x0d;
    private static final int LF = 0x0a;
    private static final int EOF = 0x1a;
    // block size - DON'T CHANGE - I toyed with the idea of adding 1K support but the code is NOT there yet.
    private static final int bs = 128;
    // PRIVATE STUFF
    private int ebn; // expected incoming block #
    private byte[] data; // our data buffer
    private int dataPos; // our position with the data buffer
    private InputStream in;
    private OutputStream out;
    * Creates a new InputStream allowing you to read the incoming file. All of the XModem
    * protocol functions are handled transparently.
    * As soon as this class is instantiated, it will attempt to iniatate the transfer
    * with the remote computer - if unsuccessful, an IOException will be thrown. If it
    * is successful, reading may commense.
    * NOTE: It is important not to wait too long in between calls to read() - the remote
    * computer will resend a data block if too much time has passed or even just give up
    * on the transfer altogether.
    * @param in InputStream from Serial Line
    * @param out OutputStream from Serial Line
    public XModemRXStream(InputStream in, OutputStream out) throws
    IOException {
    this.in = in;
    this.out = out;
    // Initiate the receive sequence - basically, we send a NAK until the data
    // starts flowing.
    init:for (int t = 0; t < 10; t++) {
    if (XModem.debug) {
    System.out.println("Waiting for response [ try #" + t + " ]");
    long mark = System.currentTimeMillis();
    out.write(NAK);
    // Frequently check to see if the data is flowing, give up after a couple seconds.
    for (; ; ) {
    if (in.available() > 0) {
    break init;
    try {
    Thread.sleep(10);
    catch (Exception e) {}
    if (System.currentTimeMillis() - mark > 2000) {
    break;
    // We have either successfully negotiated the transfer, OR, it was
    // a failure and timed out. Check in.available() to see if we have incoming
    // bytes and that will be our sign.
    if (in.available() == 0) {
    throw new IOException();
    // Initialize some stuff
    ebn = 1; // the first block we see should be #1
    data = new byte[bs];
    dataPos = bs;
    * Reads the next block of data from the remote computer. Most of the real XModem protocol
    * is encapsulated within this method.
    * @throws IOException
    private synchronized void getNextBlock() throws IOException {
    if (XModem.debug) {
    //System.out.println("Getting block #" + ebn);
    // Read block into buffer. There is a 1 sec timeout for each character,
    // otherwise we NAK and start over.
    byte[] buffer;
    recv:for (; ; ) {
    buffer = new byte[bs + 4];
    for (int t = 0; t < 10; t++) {
    System.out.println("\nReceiving block [ #" + ebn + " ]");
    // Read in block
    buffer = new byte[buffer.length];
    for (int i = 0; i < buffer.length; i++) {
    int b = readTimed(1);
    // if EOT - don't worry about the rest of the block.
    if ( (i == 0) && (b == EOT)) {
    buffer[0] = (byte) (b & 0xff);
    break;
    // if CAN - the other side has cancelled the transfer
    if (b == CAN) {
    throw new IOException("cancelled");
    if (b < 0) {
    if (XModem.debug) {
    System.out.println("Time out... NAK'ing");
    out.write(NAK);
    continue recv;
    else {
    buffer[i] = (byte) (b & 0xFF);
    break;
    int type = buffer[0] & 0xff; // either SOH or EOT
    if (type == EOT) {
    if (XModem.debug) {
    System.out.println("EOT!");
    out.write(ACK);
    break;
    int bn = buffer[1] & 0xff; // block number
    int bnc = buffer[2] & 0xff; // one's complement to block #
    if (
    (bn != ebn) && (bn != (ebn - 1)) ||
    (bn + bnc != 255)) {
    if (XModem.debug) {
    System.out.println("NAK'ing type = " + type + " bn = " + bn +
    " ebn = " +
    ebn + " bnc = " + bnc);
    out.write(NAK);
    continue recv;
    byte chksum = buffer[ (buffer.length - 1)];
    byte echksum = 0;
    for (int i = 3; i < (buffer.length - 1); i++) {
    echksum = (byte) ( ( (echksum & 0xff) + (buffer[i] & 0xff)) & 0xff);
    if (chksum != echksum) {
    out.write(NAK);
    continue recv;
    out.write(ACK);
    if (ebn == 255) {
    ebn = 0;
    else {
    ebn++;
    break;
    // We got our block, now save it in our data buffer.
    data = new byte[bs];
    for (int i = 3; i < (buffer.length - 1); i++) {
    data[(i - 3)] = buffer;
    dataPos = 0;
    public synchronized int read() throws IOException {
    // If at the end of our buffer, refill it.
    if (dataPos == bs) {
    try {
    getNextBlock();
    catch (IOException e) {
    throw new IOException();
    // If we're still at end of buffer, say so.
    if ( dataPos == bs) {
    return -1;
    int d = data[dataPos];
    if (d == EOF)
    return -1;
    dataPos++;
    return d;
    * A wrapper around the native read() call that provides the ability
    * to timeout if no data is available within the specified timeout value.
    * @param timeout timeout value in seconds
    * @throws IOException
    * @return int an integer representing the byte value read.
    private int readTimed(int timeout) throws IOException {
    long start = System.currentTimeMillis();
    for (; ; ) {
    if (in.available() > 0) {
    return (in.read());
    try {
    Thread.sleep(10);
    catch (InterruptedException ex) {
    //if (System.currentTimeMillis() - start > timeout * 1000) {
    if (System.currentTimeMillis() - start > timeout * 5000) {
    return -1;
    Here was the output...
    Original file:
    (Commodore CBM SEQ file exported to PC using DirMaster)
    ��
    � �
    � ��� �� �� ��� ��
    � �� �� ���� �� ��� ��
    � ��� ����������������������������������������������
    �� ����� ������� ����� �� ����� ������ ����� ���
    � �� ������ ������ ��� ��� �� ��� ���� �� ������
    � � ���
    ����
    � � ��OWERED BY �OLOR 64 ��� V8
    �UNNING �ETWORK64 V1.26A

    �UPPORTING 38400 �AUD �ATES
    �����/����/�������

    �ESTING �CHO-�ET V1 BETA

    �EATURING �ESSAGES, �ILES,
    �ET�AIL, AND �NLINE �AMES!
    �YS�P: � � � � � � � � �

    �RESS ANY KEY TO LOGIN\C�
    The result when the file was uploaded and received by my XServer:
    ? ? ??OWERED BY ?OLOR 64 ??? V8
    ?UNNING ?ETWORK64 V1.26A
    ?UPPORTING 38400 ?AUD ?ATES
    ?ESTING ?CHO-?ET V1 BETA
    ?EATURING ?ESSAGES, ?ILES,
    ?ET?AIL, AND ?NLINE ?AMES!
    ?YS?P: ? ? ? ? ? ? ? ? ?
    ?RESS ANY KEY TO LOGIN\C?
    The result is different!
    Can someone help me along here... I have been trying to figure out how to do this for approx. a year or so... it has been a very slow process.
    I could use a guru to help me out so I can write the upload and download routines for my Commodore BBS PETSCII Emulation Server.
    Visit http://www.retrogradebbs.com for details.
    Thanks.
    Please help out a dedicated developer who is in over his head...
    -Dave

    Ok. Fair enough. What about general information about Xmodem. This is a hard project because of how obscure the legacy technology is that I am having to implement using Java and MySQL.
    I have two major issues which I have to figure out how to troubleshoot and debug, if possible.
    1. The 23+ blocks exception when a file is being received
    2. The exception which is thrown immediately if I try to receive a binary file instead of an ASCII file.
    I read that telnet is a 7-bit technology and that is why Xmodem, which is an 8-bit technology is not that popular as a viable protocol via telnet, whereas Kermit is, since it was developed for 7-bit systems, i.e. mainframes and minicomputers.
    Is this correct?
    If that is the case, why does www.serio.com have a viable X-Y-ZModem library available (for several hundred $$$ of course) which can be used with both RS-232 serial ports and TCP socket ports? Obviously, it can be done. They are the ONLY company with this library for sale for Java to do this. I cannot justify that $$$ amount for a mere hobby (writing the BBS emulation server for supporting Commodore PETSCII (CG) callers via CGTerm or a native C-64 terminal program using Jim Brain's TCPSER middleware, which emulates a Hayes modem via telnet for telBBSing/retrocomputing.
    I really want to learn how to implement a file transfer protocol, since back in the 80s, I used Xmodem, Punter, Y/Z Modem, etc., a lot to upload and download files via modem at baud rates of 2400, 14.4, 19.2, and 38.4, respectively.
    It's fun to learn how the old skool gurus of telecommunications technology did it. It is one thing to run a BBS which supports these technologies and features, and it is an entirely other thing to learn how to design and develop them yourself for implementation into a project such as I taken on.
    It CAN be done. It WILL be done. However, I have just started my exhaustive research on how it needs to be done. I have read up as much as I could on XModem by Ward C., the father of the protocol.
    But, I have no information to help me figure out why the communications are acting as they do so far.
    Can someone please download the xserver.zip file on my website at:
    www.retrogradebbs.com/projects/xserver.zip
    Compile it. Run it. Connect using HyperTerminal, Netrunner, or another telnet terminal emulation program which supports Xmodem file transfers using WinSock.
    See what happens. With finals due in the next two days, this project will have to be put on hold until after I submit my two final projects.
    If anyone knows what needs to be done to support both ASCII and BINARY file transfers via Xmodem via a socket instead of a modem with RTS/CTS hardware flow control, please respond.
    I know for a fact that this can be done.
    - Dave

  • Getting the data from a TCP/IP packet

    I am dealing with an industrial network that sends and recieves data over TCP/IP between a sort of supervisory system running on Unix and some machines via a bridge that converts messages onto other non TCP/IP networks. This is all old legacy equipment and the bridge now need upgrading. However the original source code is not availiable and no-one is very sure of the messages being sent. I thought it was going to be easy knocking something together in Java to intercept these messages and test various things but have come up against big problems.
    The main problem being that all the data is binary meaning I cant use any of the reader or writer classes I am used too. I am trying to use either DataInputStream or BufferedInputStream to read data in but am struggling. Idealy I need to be able to read (once) the complete data content of each packet that is sent and I need to tell each time a new packet of data arrives so that I can process it as a complete packet. As far as I know there are no eof or eol or any other details that tell me how many bytes of data there are, and they do vary in length, but each packet is a seperate message or message reply.
    I was hoping that there might be someway of getting this information from the TCP/IP layers but cant see how to do it as that all seems to work invisibly. Nor can I see any methods to call on the stream classes that indicate how to tell the lenght of the latest packet or when a new packet has arrived. I am not sure how some of the methods like mark() and reset|() are supposed to be used so am not sure if I couuld use these but am desperate for any help or pointers in the right direction.

    The TCP/IP packets can represent complete messagesThere is no guarantee to this effect anywhere in TCP/IP. Consider the case where a single message requires multiple writes. Consider the case where a write contains the end of one message and the beginning of another. Consider the case where there are multiple messages in a single packet. Consider ... There are just too many of these cases.
    The TCP/IP takes care of numbering the packets so that they can be reasembled in the correct order. Each TCP/IP packet contains information about the size of data the packet contains ...Thank you, I do know how TCP works.
    so in theory if we could get at the TCP/IP layers we should be able to get this information.No. You can get all the packet information out of packets. What you can't get is message information, because it isn't in there. It's in the application protocol, which to TCP/IP is just a stream of bytes. You can get the stream of bytes that the application sent. What it means is up to you.
    I really need to be able to read each packet of data seperately to be able to do anything with itWhy? Given the lack of correlation between writes() and packets and reads() due to TCP streaming, what is the point? And if you want packets you already have them via your sniffer.
    From your first post:
    each packet is a seperate message or message reply.You can't rely on that. There is no guarantee of this anywhere in TCP/IP.
    I also direct your attention to the Nagle algorithm, which coalesces outgoing packets under common conditions.

  • TCP/IP does not let me enable or disable.

    Hi, 
    I am trying to enable TCP/IP in order to access my SQL server remotely but when I select tcp/ip and want to enable = Yes or disabled = no it does not give me the option, it appears a gray empty rectangle. 
    Any idea what might happen?, I will like to post a picture but it does not let me at the moment
    Thank you,

    This one may help.
    Enable Named Pipes and TCP/IP Connections
     Might also ask them over here.
    SQL Server forums on MSDN
    Regards, Dave Patrick ....
    Microsoft Certified Professional
    Microsoft MVP [Windows]
    Disclaimer: This posting is provided "AS IS" with no warranties or guarantees , and confers no rights.

  • Async tcp client and server. How can I determine that the client or the server is no longer available?

    Hello. I would like to write async tcp client and server. I wrote this code but a have a problem, when I call the disconnect method on client or stop method on server. I can't identify that the client or the server is no longer connected.
    I thought I will get an exception if the client or the server is not available but this is not happening.
    private async void Process()
    try
    while (true)
    var data = await this.Receive();
    this.NewMessage.SafeInvoke(Encoding.ASCII.GetString(data));
    catch (Exception exception)
    How can I determine that the client or the server is no longer available?
    Server
    public class Server
    private readonly Dictionary<IPEndPoint, TcpClient> clients = new Dictionary<IPEndPoint, TcpClient>();
    private readonly List<CancellationTokenSource> cancellationTokens = new List<CancellationTokenSource>();
    private TcpListener tcpListener;
    private bool isStarted;
    public event Action<string> NewMessage;
    public async Task Start(int port)
    this.tcpListener = TcpListener.Create(port);
    this.tcpListener.Start();
    this.isStarted = true;
    while (this.isStarted)
    var tcpClient = await this.tcpListener.AcceptTcpClientAsync();
    var cts = new CancellationTokenSource();
    this.cancellationTokens.Add(cts);
    await Task.Factory.StartNew(() => this.Process(cts.Token, tcpClient), cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
    public void Stop()
    this.isStarted = false;
    foreach (var cancellationTokenSource in this.cancellationTokens)
    cancellationTokenSource.Cancel();
    foreach (var tcpClient in this.clients.Values)
    tcpClient.GetStream().Close();
    tcpClient.Close();
    this.clients.Clear();
    public async Task SendMessage(string message, IPEndPoint endPoint)
    try
    var tcpClient = this.clients[endPoint];
    await this.Send(tcpClient.GetStream(), Encoding.ASCII.GetBytes(message));
    catch (Exception exception)
    private async Task Process(CancellationToken cancellationToken, TcpClient tcpClient)
    try
    var stream = tcpClient.GetStream();
    this.clients.Add((IPEndPoint)tcpClient.Client.RemoteEndPoint, tcpClient);
    while (!cancellationToken.IsCancellationRequested)
    var data = await this.Receive(stream);
    this.NewMessage.SafeInvoke(Encoding.ASCII.GetString(data));
    catch (Exception exception)
    private async Task Send(NetworkStream stream, byte[] buf)
    await stream.WriteAsync(BitConverter.GetBytes(buf.Length), 0, 4);
    await stream.WriteAsync(buf, 0, buf.Length);
    private async Task<byte[]> Receive(NetworkStream stream)
    var lengthBytes = new byte[4];
    await stream.ReadAsync(lengthBytes, 0, 4);
    var length = BitConverter.ToInt32(lengthBytes, 0);
    var buf = new byte[length];
    await stream.ReadAsync(buf, 0, buf.Length);
    return buf;
    Client
    public class Client
    private TcpClient tcpClient;
    private NetworkStream stream;
    public event Action<string> NewMessage;
    public async void Connect(string host, int port)
    try
    this.tcpClient = new TcpClient();
    await this.tcpClient.ConnectAsync(host, port);
    this.stream = this.tcpClient.GetStream();
    this.Process();
    catch (Exception exception)
    public void Disconnect()
    try
    this.stream.Close();
    this.tcpClient.Close();
    catch (Exception exception)
    public async void SendMessage(string message)
    try
    await this.Send(Encoding.ASCII.GetBytes(message));
    catch (Exception exception)
    private async void Process()
    try
    while (true)
    var data = await this.Receive();
    this.NewMessage.SafeInvoke(Encoding.ASCII.GetString(data));
    catch (Exception exception)
    private async Task Send(byte[] buf)
    await this.stream.WriteAsync(BitConverter.GetBytes(buf.Length), 0, 4);
    await this.stream.WriteAsync(buf, 0, buf.Length);
    private async Task<byte[]> Receive()
    var lengthBytes = new byte[4];
    await this.stream.ReadAsync(lengthBytes, 0, 4);
    var length = BitConverter.ToInt32(lengthBytes, 0);
    var buf = new byte[length];
    await this.stream.ReadAsync(buf, 0, buf.Length);
    return buf;

    Hi,
    Have you debug these two applications? Does it go into the catch exception block when you close the client or the server?
    According to my test, it will throw an exception when the client or the server is closed, just log the exception message in the catch block and then you'll get it:
    private async void Process()
    try
    while (true)
    var data = await this.Receive();
    this.NewMessage.Invoke(Encoding.ASCII.GetString(data));
    catch (Exception exception)
    Console.WriteLine(exception.Message);
    Unable to read data from the transport connection: An existing   connection was forcibly closed by the remote host.
    By the way, I don't know what the SafeInvoke method is, it may be an extension method, right? I used Invoke instead to test it.
    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

  • DOM Programming in class for ABAP Mapping?

    Hi All!! I am struggling in transforming XML to be mapping target structures in using ABAP Mapping. so i am on developing class with DOM. i would like to know how many <person> derived from source xml, so what method should i use so that i can get th

  • Different values beetween front page and saved data

    Hello, I have problems to saved data correctly. I acquire data with Labview 6.0 and a counter/timer card. These data appear on my front page. But when I save them in a table file, their format is modified, rounded. For exemple: on my front page value

  • Not "Keeping files organised"

    Although this can't be a new problem, a search didn't give me an answer. I do not want iTines to organise my music, in particular I do not want it in sub folders. I want to keep it all in one folder. I used to have two main music folders, and when I

  • Batch with multiple actions.. Watermarking PSD the easy way with Fireworks 8..

    I just use Fireworks 8, Fireworks CS3 always freezes after batching 30 files or so on a 4 gig machine. I'm able to take advantage of a transparent BG in PSD or PNG and insert a bg layer and foreground layer, then export to a jpeg. I haven't been able

  • Where is the jawbone Up bracelet on apples web site?

    where is the jawbone Up bracelet on apples web site?