codedistrict-blog
codedistrict-blog
Code District
1 post
Don't wanna be here? Send us removal request.
codedistrict-blog ยท 7 years ago
Text
Connecting to a server with Java
First, in order to connect to a server you need an endpoint connection between your machine and the server. This can be easily done using the Socket class in Java.
To implement it, we start by trying to create a stream socket that connects to a local host at a specified port.
Socket socket = new Socket(String host, int port);
After a stream is created, we want to communicate with the server. Let's say we are intrested in reading the available data on the server and printing it to the user. To do so, we first need to get an input stream for reading bytes from this socket.
InputStream is = socket.getInputStream();
Finally, we want to produce values scanned from the input stream, and convert them into characters using a specified charset
Scanner scan = new Scanner(is, "UTF-8");
Last, we keep on checking if the scanner has detected any next line, if so scan it and print it
The final code should look like the following:
This program connect to the atomic clock in Boulder, Colorado and return rhe time
0 notes