开发者

Java : Socket programming example

开发者 https://www.devze.com 2023-01-20 02:33 出处:网络
What is wrong with the following program to fetch time from time server. public class SocketTest { public static void main(String[] args)

What is wrong with the following program to fetch time from time server.

public class SocketTest
{  
    public static void main(String[] args)
    {
         Socket s = new Socket(“time-A.timefreq.bldrdoc.gov”, 13);
          BufferedReader in = new BufferedReader(
                  new InputStreamReader(s.getInputStream()));
       String line;
    开发者_开发知识库   do
       {    line = in.readLine();  //read line of text from socket
              if (line != null)  System.out.println(line);
       }
       while(line != null);
    }

}


The quotation-marks should be " instead of . That is, you should have

Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13);

rather than

Socket s = new Socket(“time-A.timefreq.bldrdoc.gov”, 13);

Also, you'll need to encapsulate the IO operations in a try/catch block, or declare the method to throw IOException.

Other than that I don't have much complaints. If you import the classes properly, it will print something like

55486 10-10-17 05:30:44 22 0 0 604.7 UTC(NIST) * 

This is roughly how I would have written it

import java.io.*;
import java.net.*;

public class SocketTest {
    public static void main(String[] args) {
        try {
            Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13);
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    s.getInputStream()));
            String line;
            while ((line = in.readLine()) != null)
                System.out.println(line);

            s.close();
        } catch (IOException ioex) {
            ioex.printStackTrace();
        }
    }
}

Put the s.close() inside a finally block if you're picky and the program is larger than just a test-program like this one.


You need to use double quotes (") to enclose the strings, looks like you are using inverted quotes:

new Socket(“time-A.timefreq.bldrdoc.gov”, 13);
           ^                           ^


This example might help https://github.com/bitsabhi/DemoChatApp User ServerSocket at server side and Socket at android client side

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号