Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #16014 > unrolled thread

serversocket

Started byLucyann Lenon Emerick De Assis <lucyann.lenon@gmail.com>
First post2012-07-14 05:41 -0700
Last post2012-07-16 13:59 -0700
Articles 12 — 6 participants

Back to article view | Back to comp.lang.java.programmer


Contents

  serversocket Lucyann Lenon Emerick De Assis <lucyann.lenon@gmail.com> - 2012-07-14 05:41 -0700
    Re: serversocket Joerg Meier <joergmmeier@arcor.de> - 2012-07-14 16:40 +0200
      Re: serversocket Lew <noone@lewscanon.com> - 2012-07-14 13:04 -0700
        Re: serversocket Joerg Meier <joergmmeier@arcor.de> - 2012-07-15 00:42 +0200
    Re: serversocket Lucyann Lenon Emerick De Assis <lucyann.lenon@gmail.com> - 2012-07-14 07:56 -0700
      Re: serversocket Knute Johnson <nospam@rabbitbrush.frazmtn.com> - 2012-07-14 10:23 -0700
        Re: serversocket Martin Gregorie <martin@address-in-sig.invalid> - 2012-07-15 00:29 +0000
      Re: serversocket Lew <noone@lewscanon.com> - 2012-07-14 14:04 -0700
        Re: serversocket Lew <noone@lewscanon.com> - 2012-07-14 14:12 -0700
          Re: serversocket Lucyann Lenon Emerick De Assis <lucyann.lenon@gmail.com> - 2012-07-16 04:49 -0700
            Re: serversocket Lucyann Lenon Emerick De Assis <lucyann.lenon@gmail.com> - 2012-07-16 04:54 -0700
              Re: serversocket Lew <lewbloch@gmail.com> - 2012-07-16 13:59 -0700

#16014 — serversocket

FromLucyann Lenon Emerick De Assis <lucyann.lenon@gmail.com>
Date2012-07-14 05:41 -0700
Subjectserversocket
Message-ID<15b1bc5d-160d-4048-8ad7-2cff9cf862e0@googlegroups.com>
Bom dia! 
to começando com java mas no entanto já tenho uma certa experiência com php. to tentando criar um serversocket com java para receber dados de um gps modelo tk102 , fiz a classe abaixo que por sinal esta "funcionando" eu emulei o modelo dele no meu smart e ele fez o que tinha que fazer leu e imprimiu em tela os logs, entretanto quando eu coloco o gps pra conectar ele nao conect. sei que ele esta funcionando pois em um forum na net um cara me forneceu o ip do server dele e nele conectou. alguem pode me ajudar ?



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Track {

    public static void main(String[] args) {

        //Declaro o ServerSocket  
        ServerSocket serv = null;

        //Declaro o Socket de comunicação  
        Socket s = null;

        //Declaro o leitor para a entrada de dados  
        BufferedReader entrada = null;

        while (true) {

            try {

                //Cria o ServerSocket na porta 11000 se estiver disponível  
                serv = new ServerSocket(11000);

                //Aguarda uma conexão na porta especificada e cria retorna o socket que irá comunicar com o cliente  
                s = serv.accept();

 //Cria um BufferedReader para o canal da stream de entrada de dados do socket s  
                entrada = new BufferedReader(new InputStreamReader(s.getInputStream()));

                //Aguarda por algum dado e imprime a linha recebida quando recebe  
                System.out.println(entrada.readLine());

                //trata possíveis excessões de input/output. Note que as excessões são as mesmas utilizadas para as classes de java.io    
            } catch (IOException e) {

                //Imprime uma notificação na saída padrão caso haja algo errado.  
                System.out.println("Algum problema ocorreu para criar ou receber o socket.");

            } finally {

                try {

                    //Encerro o socket de comunicação  
                    s.close();

                    //Encerro o ServerSocket  
                    serv.close();

                } catch (IOException e) {
                }
            }
        }



    }
}

[toc] | [next] | [standalone]


#16017

FromJoerg Meier <joergmmeier@arcor.de>
Date2012-07-14 16:40 +0200
Message-ID<5nah2kz4u5lh.q6uivtfnl4l2$.dlg@40tude.net>
In reply to#16014
On Sat, 14 Jul 2012 05:41:27 -0700 (PDT), Lucyann Lenon Emerick De Assis
wrote:

> Bom dia! 
> to começando com java mas no entanto já tenho uma certa experiência com php. to tentando criar um serversocket com java para receber dados de um gps modelo tk102 , fiz a classe abaixo que por sinal esta "funcionando" eu emulei o modelo dele no meu smart e ele fez o que tinha que fazer leu e imprimiu em tela os logs, entretanto quando eu coloco o gps pra conectar ele nao conect. sei que ele esta funcionando pois em um forum na net um cara me forneceu o ip do server dele e nele conectou. alguem pode me ajudar ?

Hallo!

Das ist ein sehr interessantes Schreiben, was Sie da veroeffentlichen.
Leider spreche ich Ihre Sprache nicht, genau so, wie Sie vermutlich meine
nicht sprechen. Daher ist es sinnvoll, Schreiben in einer der Gruppe
angepassten Sprache zu veroeffentlichen.

Liebe Gruesse,
		Joerg

-- 
Ich lese meine Emails nicht, replies to Email bleiben also leider
ungelesen.

[toc] | [prev] | [next] | [standalone]


#16026

FromLew <noone@lewscanon.com>
Date2012-07-14 13:04 -0700
Message-ID<jtsjc3$4ki$2@news.albasani.net>
In reply to#16017
Joerg Meier wrote:
> Lucyann Lenon Emerick De Assis wrote:
>
>> Bom dia!
>> to começando com java mas no entanto já tenho uma certa experiência com php. to tentando criar um serversocket com java para receber dados de um gps modelo tk102 , fiz a classe abaixo que por sinal esta "funcionando" eu emulei o modelo dele no meu smart e ele fez o que tinha que fazer leu e imprimiu em tela os logs, entretanto quando eu coloco o gps pra conectar ele nao conect. sei que ele esta funcionando pois em um forum na net um cara me forneceu o ip do server dele e nele conectou. alguem pode me ajudar ?
>
> Hallo!
>
> Das ist ein sehr interessantes Schreiben, was Sie da veroeffentlichen.
> Leider spreche ich Ihre Sprache nicht, genau so, wie Sie vermutlich meine
> nicht sprechen. Daher ist es sinnvoll, Schreiben in einer der Gruppe
> angepassten Sprache zu veroeffentlichen.

Really, Joerg? You couldn't pipe that through Google Translate

http://translate.google.com
?

-- 
Lew
Honi soit qui mal y pense.
http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg

[toc] | [prev] | [next] | [standalone]


#16029

FromJoerg Meier <joergmmeier@arcor.de>
Date2012-07-15 00:42 +0200
Message-ID<1xxlgyuzcdkjz.1q84kvzxr5ndm.dlg@40tude.net>
In reply to#16026
On Sat, 14 Jul 2012 13:04:55 -0700, Lew wrote:

> Joerg Meier wrote:
>> Lucyann Lenon Emerick De Assis wrote:
>>> Bom dia!
>>> to começando com java mas no entanto já tenho uma certa experiência com php. to tentando criar um serversocket com java para receber dados de um gps modelo tk102 , fiz a classe abaixo que por sinal esta "funcionando" eu emulei o modelo dele no meu smart e ele fez o que tinha que fazer leu e imprimiu em tela os logs, entretanto quando eu coloco o gps pra conectar ele nao conect. sei que ele esta funcionando pois em um forum na net um cara me forneceu o ip do server dele e nele conectou. alguem pode me ajudar ?
>> Hallo!

>> Das ist ein sehr interessantes Schreiben, was Sie da veroeffentlichen.
>> Leider spreche ich Ihre Sprache nicht, genau so, wie Sie vermutlich meine
>> nicht sprechen. Daher ist es sinnvoll, Schreiben in einer der Gruppe
>> angepassten Sprache zu veroeffentlichen.
> Really, Joerg? You couldn't pipe that through Google Translate

> http://translate.google.com

Really, Lew, I could.

Liebe Gruesse,
		Joerg

-- 
Ich lese meine Emails nicht, replies to Email bleiben also leider
ungelesen.

[toc] | [prev] | [next] | [standalone]


#16018

FromLucyann Lenon Emerick De Assis <lucyann.lenon@gmail.com>
Date2012-07-14 07:56 -0700
Message-ID<76cf48db-123d-4888-ac60-4b80ccfdeea4@googlegroups.com>
In reply to#16014
translating
Good morning!
to starting with java but Nevertheless I have some experience with php. Trying to create a ServerSocket with java to get data from the GPS model TK102, did the class below That by the way this "working" I emulei the model of it on my smart and he did what he HAD to read on screen and printed logs , However when i put the gps to connect it does not conect. I know he is working as a forum on the net a guy Gave me the ip of the server and connected it hin. Can someone help me?
Em sábado, 14 de julho de 2012 09h41min27s UTC-3, Lucyann Lenon Emerick De Assis  escreveu:
> Bom dia! 
> to começando com java mas no entanto já tenho uma certa experiência com php. to tentando criar um serversocket com java para receber dados de um gps modelo tk102 , fiz a classe abaixo que por sinal esta &quot;funcionando&quot; eu emulei o modelo dele no meu smart e ele fez o que tinha que fazer leu e imprimiu em tela os logs, entretanto quando eu coloco o gps pra conectar ele nao conect. sei que ele esta funcionando pois em um forum na net um cara me forneceu o ip do server dele e nele conectou. alguem pode me ajudar ?
> 
> 
> 
> import java.io.BufferedReader;
> import java.io.IOException;
> import java.io.InputStreamReader;
> import java.net.ServerSocket;
> import java.net.Socket;
> 
> public class Track {
> 
>     public static void main(String[] args) {
> 
>         //Declaro o ServerSocket  
>         ServerSocket serv = null;
> 
>         //Declaro o Socket de comunicação  
>         Socket s = null;
> 
>         //Declaro o leitor para a entrada de dados  
>         BufferedReader entrada = null;
> 
>         while (true) {
> 
>             try {
> 
>                 //Cria o ServerSocket na porta 11000 se estiver disponível  
>                 serv = new ServerSocket(11000);
> 
>                 //Aguarda uma conexão na porta especificada e cria retorna o socket que irá comunicar com o cliente  
>                 s = serv.accept();
> 
>  //Cria um BufferedReader para o canal da stream de entrada de dados do socket s  
>                 entrada = new BufferedReader(new InputStreamReader(s.getInputStream()));
> 
>                 //Aguarda por algum dado e imprime a linha recebida quando recebe  
>                 System.out.println(entrada.readLine());
> 
>                 //trata possíveis excessões de input/output. Note que as excessões são as mesmas utilizadas para as classes de java.io    
>             } catch (IOException e) {
> 
>                 //Imprime uma notificação na saída padrão caso haja algo errado.  
>                 System.out.println(&quot;Algum problema ocorreu para criar ou receber o socket.&quot;);
> 
>             } finally {
> 
>                 try {
> 
>                     //Encerro o socket de comunicação  
>                     s.close();
> 
>                     //Encerro o ServerSocket  
>                     serv.close();
> 
>                 } catch (IOException e) {
>                 }
>             }
>         }
> 
> 
> 
>     }
> }

[toc] | [prev] | [next] | [standalone]


#16022

FromKnute Johnson <nospam@rabbitbrush.frazmtn.com>
Date2012-07-14 10:23 -0700
Message-ID<jts9va$r6p$1@dont-email.me>
In reply to#16018
On 7/14/2012 7:56 AM, Lucyann Lenon Emerick De Assis wrote:
> translating
> Good morning!
> to starting with java but Nevertheless I have some experience with php. Trying to create a ServerSocket with java to get data from the GPS model TK102, did the class below That by the way this "working" I emulei the model of it on my smart and he did what he HAD to read on screen and printed logs , However when i put the gps to connect it does not conect. I know he is working as a forum on the net a guy Gave me the ip of the server and connected it hin. Can someone help me?
> Em sábado, 14 de julho de 2012 09h41min27s UTC-3, Lucyann Lenon Emerick De Assis  escreveu:
>> Bom dia!
>> to começando com java mas no entanto já tenho uma certa experiência com php. to tentando criar um serversocket com java para receber dados de um gps modelo tk102 , fiz a classe abaixo que por sinal esta &quot;funcionando&quot; eu emulei o modelo dele no meu smart e ele fez o que tinha que fazer leu e imprimiu em tela os logs, entretanto quando eu coloco o gps pra conectar ele nao conect. sei que ele esta funcionando pois em um forum na net um cara me forneceu o ip do server dele e nele conectou. alguem pode me ajudar ?
>>
>>
>>
>> import java.io.BufferedReader;
>> import java.io.IOException;
>> import java.io.InputStreamReader;
>> import java.net.ServerSocket;
>> import java.net.Socket;
>>
>> public class Track {
>>
>>      public static void main(String[] args) {
>>
>>          //Declaro o ServerSocket
>>          ServerSocket serv = null;
>>
>>          //Declaro o Socket de comunicação
>>          Socket s = null;
>>
>>          //Declaro o leitor para a entrada de dados
>>          BufferedReader entrada = null;
>>
>>          while (true) {
>>
>>              try {
>>
>>                  //Cria o ServerSocket na porta 11000 se estiver disponível
>>                  serv = new ServerSocket(11000);
>>
>>                  //Aguarda uma conexão na porta especificada e cria retorna o socket que irá comunicar com o cliente
>>                  s = serv.accept();
>>
>>   //Cria um BufferedReader para o canal da stream de entrada de dados do socket s
>>                  entrada = new BufferedReader(new InputStreamReader(s.getInputStream()));
>>
>>                  //Aguarda por algum dado e imprime a linha recebida quando recebe
>>                  System.out.println(entrada.readLine());
>>
>>                  //trata possíveis excessões de input/output. Note que as excessões são as mesmas utilizadas para as classes de java.io
>>              } catch (IOException e) {
>>
>>                  //Imprime uma notificação na saída padrão caso haja algo errado.
>>                  System.out.println(&quot;Algum problema ocorreu para criar ou receber o socket.&quot;);
>>
>>              } finally {
>>
>>                  try {
>>
>>                      //Encerro o socket de comunicação
>>                      s.close();
>>
>>                      //Encerro o ServerSocket
>>                      serv.close();
>>
>>                  } catch (IOException e) {
>>                  }
>>              }
>>          }
>>
>>
>>
>>      }
>> }

A ServerSocket is used when you want to be the server.  A Socket is used 
when you want to connect to a server.  Is the GPS running a server?

[toc] | [prev] | [next] | [standalone]


#16030

FromMartin Gregorie <martin@address-in-sig.invalid>
Date2012-07-15 00:29 +0000
Message-ID<jtt2sl$qce$1@localhost.localdomain>
In reply to#16022
On Sat, 14 Jul 2012 10:23:52 -0700, Knute Johnson wrote:

> On 7/14/2012 7:56 AM, Lucyann Lenon Emerick De Assis wrote:
>> translating Good morning!
>> to starting with java but Nevertheless I have some experience with php.
>> Trying to create a ServerSocket with java to get data from the GPS
>> model TK102, did the class below That by the way this "working" I
>> emulei the model of it on my smart and he did what he HAD to read on
>> screen and printed logs , However when i put the gps to connect it does
>> not conect. I know he is working as a forum on the net a guy Gave me
>> the ip of the server and connected it hin. Can someone help me?
>> Em sábado, 14 de julho de 2012 09h41min27s UTC-3, Lucyann Lenon Emerick
>> De Assis  escreveu:
>>> Bom dia!
>>> to começando com java mas no entanto já tenho uma certa experiência
>>> com php. to tentando criar um serversocket com java para receber dados
>>> de um gps modelo tk102 , fiz a classe abaixo que por sinal esta
>>> &quot;funcionando&quot; eu emulei o modelo dele no meu smart e ele fez
>>> o que tinha que fazer leu e imprimiu em tela os logs, entretanto
>>> quando eu coloco o gps pra conectar ele nao conect. sei que ele esta
>>> funcionando pois em um forum na net um cara me forneceu o ip do server
>>> dele e nele conectou. alguem pode me ajudar ?
>>>
>>>
>>>
>>> import java.io.BufferedReader;
>>> import java.io.IOException;
>>> import java.io.InputStreamReader;
>>> import java.net.ServerSocket;
>>> import java.net.Socket;
>>>
>>> public class Track {
>>>
>>>      public static void main(String[] args) {
>>>
>>>          //Declaro o ServerSocket ServerSocket serv = null;
>>>
>>>          //Declaro o Socket de comunicação Socket s = null;
>>>
>>>          //Declaro o leitor para a entrada de dados BufferedReader
>>>          entrada = null;
>>>
>>>          while (true) {
>>>
>>>              try {
>>>
>>>                  //Cria o ServerSocket na porta 11000 se estiver
>>>                  disponível serv = new ServerSocket(11000);
>>>
>>>                  //Aguarda uma conexão na porta especificada e cria
>>>                  retorna o socket que irá comunicar com o cliente s =
>>>                  serv.accept();
>>>
>>>   //Cria um BufferedReader para o canal da stream de entrada de dados
>>>   do socket s
>>>                  entrada = new BufferedReader(new
>>>                  InputStreamReader(s.getInputStream()));
>>>
>>>                  //Aguarda por algum dado e imprime a linha recebida
>>>                  quando recebe System.out.println(entrada.readLine());
>>>
>>>                  //trata possíveis excessões de input/output. Note que
>>>                  as excessões são as mesmas utilizadas para as classes
>>>                  de java.io
>>>              } catch (IOException e) {
>>>
>>>                  //Imprime uma notificação na saída padrão caso haja
>>>                  algo errado.
>>>                  System.out.println(&quot;Algum problema ocorreu para
>>>                  criar ou receber o socket.&quot;);
>>>
>>>              } finally {
>>>
>>>                  try {
>>>
>>>                      //Encerro o socket de comunicação s.close();
>>>
>>>                      //Encerro o ServerSocket serv.close();
>>>
>>>                  } catch (IOException e) {
>>>                  }
>>>              }
>>>          }
>>>
>>>
>>>
>>>      }
>>> }
> 
> A ServerSocket is used when you want to be the server.  A Socket is used
> when you want to connect to a server.  Is the GPS running a server?
>
I've found a set of variations on a sort-of spec for the TK-102 which 
don't shed a lot of light. The thing is a vehicle or person tracker: 
you're meant to stick a SIM into it and either interrogate it via SMS or 
set it up to send you an SMS at configurable intervals to say where it 
is. It also seems to have a microphone that can be used to listen in to 
what's happening near it.

It appears that you can also talk to it via its USB socket for 
configuration, etc. This assumes you'll use something like a Windows box 
running Hyperterminal or a Linux system running minicom or Kermit. I 
gather from this that the USB connection must be a serial connection, 
which Java does not do without JNI, though I suppose you could use a 
socket connection to talk to a TCP:serial converter of some sort.

There is some talk about configuring it with an IPV4 IP, but I frankly 
don't understand this unless you can piggyback a TCP session onto GPRS 
and/or via an SMS stream and so get to it that way.

In any case it looks very much as though the TK-102 wants to be the 
server, so if it can be reached over a socket connection, it looks like 
the OP should be using a Socket rather than a ServerSocket to talk to it.


-- 
martin@   | Martin Gregorie
gregorie. | Essex, UK
org       |

[toc] | [prev] | [next] | [standalone]


#16027

FromLew <noone@lewscanon.com>
Date2012-07-14 14:04 -0700
Message-ID<jtsmrv$djo$1@news.albasani.net>
In reply to#16018
On 07/14/2012 07:56 AM, Lucyann Lenon Emerick De Assis wrote:
> Trying to create a ServerSocket with java

It's spelled "Java", not "java".

> to get data from the GPS model TK102, did the class below
> That by the way this "working" I emulei the model of it on my smart
> and he did what he HAD to read on screen and printed logs , However
> when i put the gps to connect it does not conect. I know he is working

Actually, the code you show is riddled with bugs and potential bugs.

I don't know what you mean by "working", but it isn't what I mean.

> as a forum on the net a guy Gave me the ip of the server and connected it hin.

Gave you the IP address of what server? How does another server demonstrate 
the correctness of your code?

>> import java.io.BufferedReader;
>> import java.io.IOException;
>> import java.io.InputStreamReader;
>> import java.net.ServerSocket;
>> import java.net.Socket;
>>
>> public class Track {
>>
>>      public static void main(String[] args) {
>>
>>          //Declaro o ServerSocket
>>          ServerSocket serv = null;
>>
>>          //Declaro o Socket de comunicação
>>          Socket s = null;
>>
>>          //Declaro o leitor para a entrada de dados
>>          BufferedReader entrada = null;
>>
>>          while (true) {
>>
>>              try {
>>
>>                  //Cria o ServerSocket na porta 11000 se estiver disponível
>>                  serv = new ServerSocket(11000);
>>
>>                  //Aguarda uma conexão na porta especificada e cria retorna o socket que irá comunicar com o cliente
>>                  s = serv.accept();
>>
>>   //Cria um BufferedReader para o canal da stream de entrada de dados do socket s
>>                  entrada = new BufferedReader(new InputStreamReader(s.getInputStream()));
>>
>>                  //Aguarda por algum dado e imprime a linha recebida quando recebe
>>                  System.out.println(entrada.readLine());
>>
>>                  //trata possíveis excessões de input/output. Note que as excessões são as mesmas utilizadas para as classes de java.io
>>              } catch (IOException e) {
>>
>>                  //Imprime uma notificação na saída padrão caso haja algo errado.
>>                  System.out.println(&quot;Algum problema ocorreu para criar ou receber o socket.&quot;);
>>
>>              } finally {
>>
>>                  try {
>>
>>                      //Encerro o socket de comunicação
>>                      s.close();
>>
>>                      //Encerro o ServerSocket
>>                      serv.close();
>>
>>                  } catch (IOException e) {
>>                  }
>>              }
>>          }
>>      }
>> }

First, thank you for providing such a complete example. Not everyone does. 
Those folks should take heed of

http://sscce.org/

You do tend to comment excessively, making note of things the code itself 
already documents. For example:

         //Declaro o ServerSocket
         ServerSocket serv = null;

Well, duh! Comments should be helpful, not silly. They should express what the 
code does not already make crystal clear.

I find the style of many consecutive blank lines at random points in the 
source to be disconcerting at best. What is it intended to communicate?

Also, your variable names are too terse. 's' and 'serv' are not as good 
variable names as 'socket' and 'serverSocket'.

         serverSocket = new ServerSocket(11000);

The value '11000' should be declared as a constant variable member, not 
embedded deep in the code like this, an antipattern called "magic values".

         try
         {
           s.close();
           serv.close();
         }
         catch (IOException e)
         {
         }

Don't ever ignore exceptions like that! At an absolute minimum you must log them.

Note that if 's.close();' throws an exception, 'serv.close();' will not 
execute. There's room for a bug there, in theory. (In practice I've never 
heard of such a 'close()' call failing, but it could, I suppose.)

Furthermore, you coded these resource variables in such a way as to risk a 
'NullPointerException' ("NPE"). This is a common consequence of initializing 
resource variables to 'null' and ignoring the concomitant responsibility to 
check for 'null' before calling methods on them. That's bad coding, for sure.

I find it safer to declare the variables 'final' and not initialize them to 
'null' but to the desired resource reference in a separate 'try...catch' 
block. That way you don't have to check for 'null' when you 'close()' them. 
Doing what you did is begging for bugs.

You initialize the server socket every time through the loop. That is not 
normal. You shouldn't create a new server socket every time you want to make a 
connection; you should reuse the server socket and get a new regular socket 
for each connection.

You should limit the scope of 'entrada' to the block that uses it. Declaring 
variables with too wide a scope is an invitation for bugs, and an impediment 
to the garbage collector.

I provide a rewrite taking these hints into account. As an exercise, you 
should convert all the static methods except 'main()' into instance methods. I 
gave you a head start.

The code compiles but I haven't run it.

Question: How does the client know to connect to this server?
Question: How will the client connect to this server?
Question: Please show us the client code.

/* Track
  * $RCSfile$
  */
package eegee;

/**
  * Track.
  */
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

public class Track
{
   static final Logger logger = Logger.getLogger(Track.class);
   static final int PORT = 11000;
   static final int BAD_EXIT = -1;

   static final String BAD_SERVER_SOCKET = "Unable to establish ServerSocket";
   static final String BAD_CONNECT =
       "Algum problema ocorreu para criar ou receber o socket.";
   static final String BAD_GETSTREAM = "Unable to open InputStream";
   static final String BAD_READ = "Bad read from Socket";
   static final String BAD_CLOSE = "Failure in close() call";

   /**
    * Run the Track server.
    *
    * @param args String [] of command-line arguments.
    */
   public static void main(String[] args)
   {
     final ServerSocket serverSocket;
     try
     {
       serverSocket = new ServerSocket(PORT);
     }
     catch (IOException exc)
     {
       logger.error(BAD_SERVER_SOCKET, exc);
       System.exit(BAD_EXIT);
       return; // satisfy compiler that serverSocket was initialized
     }
     assert serverSocket != null;

     try
     {
       serveConnections(serverSocket);
     }
     finally
     {
       close(serverSocket);
     }
   }

   private static void serveConnections(ServerSocket serverSocket)
   {
     while (true)
     {
       final Socket connectionSocket;
       try
       {
         connectionSocket = serverSocket.accept();
       }
       catch (IOException exc)
       {
         logger.error(BAD_CONNECT, exc);
         return;
       }
       assert connectionSocket != null;

       try
       {
         handleClient(connectionSocket);
       }
       finally
       {
         close(connectionSocket);
       }
     }
   }

   private static void handleClient(Socket connectionSocket)
   {
     final BufferedReader entrada;
     try
     {
       entrada = new BufferedReader(new InputStreamReader(
           connectionSocket.getInputStream()));
     }
     catch (IOException exc)
     {
       logger.error(BAD_GETSTREAM, exc);
       return;
     }
     assert entrada != null;

     try
     {
       String request = entrada.readLine();
       handleRequest(request);
     }
     catch (IOException exd)
     {
       logger.error(BAD_READ, exd);
     }
     finally
     {
       close(entrada);
     }
   }

   private static void handleRequest(String request)
   {
     System.out.println(request);
   }

   static void close(Closeable closeable)
   {
     try
     {
       closeable.close();
     }
     catch (IOException exc)
     {
       logger.error(BAD_CLOSE, exc);
     }
   }

   static void close(Socket closeable)
   {
     try
     {
       closeable.close();
     }
     catch (IOException exc)
     {
       logger.error(BAD_CLOSE, exc);
     }
   }

   private final int port;

   /**
    * Instantiate with the default server port.
    */
   public Track()
   {
     this(PORT);
   }

   /**
    * Instantiate with the specified server port.
    * @param port int server port.
    */
   public Track(int port)
   {
     this.port = port;
   }

   public int getPort()
   {
     return port;
   }
}

-- 
Lew
Honi soit qui mal y pense.
http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg

[toc] | [prev] | [next] | [standalone]


#16028

FromLew <noone@lewscanon.com>
Date2012-07-14 14:12 -0700
Message-ID<jtsnaj$efi$1@news.albasani.net>
In reply to#16027
Lew wrote:
  ... [snip] ...
> /* Track
>   * $RCSfile$
>   */
> package eegee;

  ...

> public class Track
> {

  ...

>    private static void serveConnections(ServerSocket serverSocket)
>    {
>      while (true)
>      {
>        final Socket connectionSocket;
>        try
>        {
>          connectionSocket = serverSocket.accept();
>        }
>        catch (IOException exc)
>        {
>          logger.error(BAD_CONNECT, exc);
>          return;
>        }
>        assert connectionSocket != null;
>
>        try
>        {
>          handleClient(connectionSocket);
>        }
>        finally
>        {
>          close(connectionSocket);
>        }
>      }
>    }
  ...

I made a mistake in the 'serveConnections()' method, arguably. Or maybe it 
isn't a mistake.

What do you think; is it a mistake or not?

-- 
Lew
Honi soit qui mal y pense.
http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg

[toc] | [prev] | [next] | [standalone]


#16042

FromLucyann Lenon Emerick De Assis <lucyann.lenon@gmail.com>
Date2012-07-16 04:49 -0700
Message-ID<c64ee38e-33db-4da9-a911-6c601fe24fdd@googlegroups.com>
In reply to#16028
Well, first I thank you for the answer, and guidelines apply to my learning!
the customer is a good model tk 102 gps, if not I engando communicates via tcp.
What struck me is that the same code works on a smartphone, I used the tracker to emulate mylive sending data tk 102
Em sábado, 14 de julho de 2012 18h12min22s UTC-3, Lew  escreveu:
> Lew wrote:
>   ... [snip] ...
> &gt; /* Track
> &gt;   * $RCSfile$
> &gt;   */
> &gt; package eegee;
> 
>   ...
> 
> &gt; public class Track
> &gt; {
> 
>   ...
> 
> &gt;    private static void serveConnections(ServerSocket serverSocket)
> &gt;    {
> &gt;      while (true)
> &gt;      {
> &gt;        final Socket connectionSocket;
> &gt;        try
> &gt;        {
> &gt;          connectionSocket = serverSocket.accept();
> &gt;        }
> &gt;        catch (IOException exc)
> &gt;        {
> &gt;          logger.error(BAD_CONNECT, exc);
> &gt;          return;
> &gt;        }
> &gt;        assert connectionSocket != null;
> &gt;
> &gt;        try
> &gt;        {
> &gt;          handleClient(connectionSocket);
> &gt;        }
> &gt;        finally
> &gt;        {
> &gt;          close(connectionSocket);
> &gt;        }
> &gt;      }
> &gt;    }
>   ...
> 
> I made a mistake in the &#39;serveConnections()&#39; method, arguably. Or maybe it 
> isn&#39;t a mistake.
> 
> What do you think; is it a mistake or not?
> 
> -- 
> Lew
> Honi soit qui mal y pense.
> http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg

[toc] | [prev] | [next] | [standalone]


#16043

FromLucyann Lenon Emerick De Assis <lucyann.lenon@gmail.com>
Date2012-07-16 04:54 -0700
Message-ID<2753cc51-51df-4a3e-b92d-21ebe6309248@googlegroups.com>
In reply to#16042
Em segunda-feira, 16 de julho de 2012 08h49min06s UTC-3, Lucyann Lenon Emerick De Assis  escreveu:
> Well, first I thank you for the answer, and guidelines apply to my learning!
> the customer is a good model tk 102 gps, if not I engando communicates via tcp.
> What struck me is that the same code works on a smartphone, I used the tracker to emulate mylive sending data tk 102
> Em sábado, 14 de julho de 2012 18h12min22s UTC-3, Lew  escreveu:
> &gt; Lew wrote:
> &gt;   ... [snip] ...
> &gt; &amp;gt; /* Track
> &gt; &amp;gt;   * $RCSfile$
> &gt; &amp;gt;   */
> &gt; &amp;gt; package eegee;
> &gt; 
> &gt;   ...
> &gt; 
> &gt; &amp;gt; public class Track
> &gt; &amp;gt; {
> &gt; 
> &gt;   ...
> &gt; 
> &gt; &amp;gt;    private static void serveConnections(ServerSocket serverSocket)
> &gt; &amp;gt;    {
> &gt; &amp;gt;      while (true)
> &gt; &amp;gt;      {
> &gt; &amp;gt;        final Socket connectionSocket;
> &gt; &amp;gt;        try
> &gt; &amp;gt;        {
> &gt; &amp;gt;          connectionSocket = serverSocket.accept();
> &gt; &amp;gt;        }
> &gt; &amp;gt;        catch (IOException exc)
> &gt; &amp;gt;        {
> &gt; &amp;gt;          logger.error(BAD_CONNECT, exc);
> &gt; &amp;gt;          return;
> &gt; &amp;gt;        }
> &gt; &amp;gt;        assert connectionSocket != null;
> &gt; &amp;gt;
> &gt; &amp;gt;        try
> &gt; &amp;gt;        {
> &gt; &amp;gt;          handleClient(connectionSocket);
> &gt; &amp;gt;        }
> &gt; &amp;gt;        finally
> &gt; &amp;gt;        {
> &gt; &amp;gt;          close(connectionSocket);
> &gt; &amp;gt;        }
> &gt; &amp;gt;      }
> &gt; &amp;gt;    }
> &gt;   ...
> &gt; 
> &gt; I made a mistake in the &amp;#39;serveConnections()&amp;#39; method, arguably. Or maybe it 
> &gt; isn&amp;#39;t a mistake.
> &gt; 
> &gt; What do you think; is it a mistake or not?
> &gt; 
> &gt; -- 
> &gt; Lew
> &gt; Honi soit qui mal y pense.
> &gt; http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg
you're telling me I have to create a client and not a server socket?, and as I receive data connection?

[toc] | [prev] | [next] | [standalone]


#16050

FromLew <lewbloch@gmail.com>
Date2012-07-16 13:59 -0700
Message-ID<e10e34ef-c63a-4f5d-aead-90feb5110966@googlegroups.com>
In reply to#16043
Lucyann Lenon Emerick De Assis wrote:
> Lew  escreveu:
>> Lew wrote:
>>  ... [snip] ...

> you're telling me I have to create a client and not a server socket?, and as I receive data connection?

No.

I am showing you how to do exactly what you did with your original
code sample, to wit, set up a socket server, with less risk of bugs 
than in your original code.

I have no idea if what you showed will do what you want. You haven't 
provided enough data that I can use to answer that.

Others have asked the relevant questions.

Namely, if the device connects to your server as a client, then you 
write the server code something along the lines shown above.

Is that how the device works?

-- 
Lew

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.java.programmer


csiph-web