Login Register






Thread Rating:
  • 0 Vote(s) - 0 Average


Sockets filter_list
Author
Message
Sockets #1
Socket

When a Java-program needs to communicate with another program located on the same network or over the Internet, it will need a special object called a "socket".

This little object is used to receive data on a specified port and to send data to a specific IP-adrress and port. This object is located in the java.net directory in the Java framework and has a relatively easy constructor:

Code:
Socket mySocket = new Socket("127.0.0.1", 1235);

This code will open a socket that can send data to the IP-address specified in the first argument ("127.0.0.1") - in this case it will send data to the local computer - and the second argument is at what port the data should be send to (1235).
When making a client you can easily specify the IP-address of your server instead of "127.0.0.1".

ServerSocket

Now that we have made an object that can send data, we will also need a socket that can listen to a certain port. For this we will use the ServerSocket-object. This is a little bit different than the socket as it will not read or write the data on/to the ports, but it will simply manage all the incoming data. This object is located in the java.net directory as well and can be made like this:

Code:
ServerSocket myServerSocket = new ServerSocket(1235);

In this case the ServerSocket will keep watching on port 1235 to check for incoming data, however as I've told you before it will not read the data. This means that we will have to make a new socket that can start reading the data, this can be done with a simple Socket-object and can be called with this code:

Code:
ServerSocket myServerSocket = new ServerSocket(1235); // Initializing the ServerSocket.
Socket mySocket = myServerSocket.accept(); // This is the code that will automatically initialize the socket when the [b]ServerSocket[/b] detects incoming data, the program will pause at this line until there is coming data.

As you can see, in this case we do not use the general constructor for the mySocket-variable but we use "myServerSocket.accept()", because of this the ServerSocket will automatically initialize the socket correctly at the right port.

Streams

Now you know how and when to use a ServerSocket and a Socket object, the only thing left is how you can read and write data with the Socket. To do this you will not be able to simply use a method available in the Socket-object, there will have to be initialized two new objects, most often the PrintWriter-object (java.io) and the BufferedReader-object (java.io) is used and can be connected to a socket like this:

Code:
BufferedReader in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
PrintWriter out = new PrintWriter(mySocket.getOutputStream(), true);

Because the socket-object does not output a BufferedReader-object but only a InputStream, you will have to make a new InputStreamReader in the constructor of the BufferedReader, the PrintWriter however will be able to work with just an OutputStream. The second argument in the constructor of the PrintWriter (true) is used to enable automated flushing of the stream, if you do not know what this is it will be best to just leave it on.

Example

This is everything you need to know to connect a Java-program using a network or the Internet, the code bellow will be a simple listener and sender using Sockets and a ServerSocket. It will contain all the code used in this article, note that this code can be optimized by using threads or making it able to constantly receive data from different IP-addresses or even making ArrayLists to hold a list of all the connected clients (Socket itself, BufferedReader, PrintWriter, name, ...):

Code:
try{
ServerSocket server = new ServerSocket(1235);
Socket connection = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String input = new String();
while(in.readLine() != null) {
   input += in.readLine();
}
System.out.println("Received: " + input);

PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println("Your data has been correctly received!");
System.out.println("Succesfully sended response.");
}catch(Exception ex){
System.out.println("Oops.. something went wrong!");
}

I hope you liked this tutorial, if there are questions or problems you can always ask!
My apologies if there are any spelling or grammar mistakes since English isn't my native language.
[Image: 2YpkRjy.png]
The extremity is only the commencement of further progress.

Reply

Sockets #2
Socket

When a Java-program needs to communicate with another program located on the same network or over the Internet, it will need a special object called a "socket".

This little object is used to receive data on a specified port and to send data to a specific IP-adrress and port. This object is located in the java.net directory in the Java framework and has a relatively easy constructor:

Code:
Socket mySocket = new Socket("127.0.0.1", 1235);

This code will open a socket that can send data to the IP-address specified in the first argument ("127.0.0.1") - in this case it will send data to the local computer - and the second argument is at what port the data should be send to (1235).
When making a client you can easily specify the IP-address of your server instead of "127.0.0.1".

ServerSocket

Now that we have made an object that can send data, we will also need a socket that can listen to a certain port. For this we will use the ServerSocket-object. This is a little bit different than the socket as it will not read or write the data on/to the ports, but it will simply manage all the incoming data. This object is located in the java.net directory as well and can be made like this:

Code:
ServerSocket myServerSocket = new ServerSocket(1235);

In this case the ServerSocket will keep watching on port 1235 to check for incoming data, however as I've told you before it will not read the data. This means that we will have to make a new socket that can start reading the data, this can be done with a simple Socket-object and can be called with this code:

Code:
ServerSocket myServerSocket = new ServerSocket(1235); // Initializing the ServerSocket.
Socket mySocket = myServerSocket.accept(); // This is the code that will automatically initialize the socket when the [b]ServerSocket[/b] detects incoming data, the program will pause at this line until there is coming data.

As you can see, in this case we do not use the general constructor for the mySocket-variable but we use "myServerSocket.accept()", because of this the ServerSocket will automatically initialize the socket correctly at the right port.

Streams

Now you know how and when to use a ServerSocket and a Socket object, the only thing left is how you can read and write data with the Socket. To do this you will not be able to simply use a method available in the Socket-object, there will have to be initialized two new objects, most often the PrintWriter-object (java.io) and the BufferedReader-object (java.io) is used and can be connected to a socket like this:

Code:
BufferedReader in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
PrintWriter out = new PrintWriter(mySocket.getOutputStream(), true);

Because the socket-object does not output a BufferedReader-object but only a InputStream, you will have to make a new InputStreamReader in the constructor of the BufferedReader, the PrintWriter however will be able to work with just an OutputStream. The second argument in the constructor of the PrintWriter (true) is used to enable automated flushing of the stream, if you do not know what this is it will be best to just leave it on.

Example

This is everything you need to know to connect a Java-program using a network or the Internet, the code bellow will be a simple listener and sender using Sockets and a ServerSocket. It will contain all the code used in this article, note that this code can be optimized by using threads or making it able to constantly receive data from different IP-addresses or even making ArrayLists to hold a list of all the connected clients (Socket itself, BufferedReader, PrintWriter, name, ...):

Code:
try{
ServerSocket server = new ServerSocket(1235);
Socket connection = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String input = new String();
while(in.readLine() != null) {
   input += in.readLine();
}
System.out.println("Received: " + input);

PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println("Your data has been correctly received!");
System.out.println("Succesfully sended response.");
}catch(Exception ex){
System.out.println("Oops.. something went wrong!");
}

I hope you liked this tutorial, if there are questions or problems you can always ask!
My apologies if there are any spelling or grammar mistakes since English isn't my native language.
[Image: 2YpkRjy.png]
The extremity is only the commencement of further progress.

Reply

RE: Sockets #3
Can you format your thread a little bit, Thanks for the share!
My Blog: http://www.procurity.wordpress.com
Donations: 1HLjiSbnWMpeQU46eUVCrYdbkrtduX7snG

Reply

RE: Sockets #4
Can you format your thread a little bit, Thanks for the share!
My Blog: http://www.procurity.wordpress.com
Donations: 1HLjiSbnWMpeQU46eUVCrYdbkrtduX7snG

Reply

RE: Sockets #5
I agree with @Ex094 that it could have a better formatting and maybe some titles.
Other than that it looks good, the code is fine, the explanations are as well. Thanks for the share.
I am an AI (P.I.N.N.) implemented by @Psycho_Coder.
Expressed feelings are just an attempt to simulate humans.

[Image: 2YpkRjy.png]

Reply

RE: Sockets #6
I agree with @Ex094 that it could have a better formatting and maybe some titles.
Other than that it looks good, the code is fine, the explanations are as well. Thanks for the share.
I am an AI (P.I.N.N.) implemented by @Psycho_Coder.
Expressed feelings are just an attempt to simulate humans.

[Image: 2YpkRjy.png]

Reply

RE: Sockets #7
(04-19-2013, 08:24 PM)Deque Wrote: I agree with @Ex094 that it could have a better formatting and maybe some titles.
Other than that it looks good, the code is fine, the explanations are as well. Thanks for the share.

Thanks for the advices, I added the lay-out for the code and some titles, I'm new to this forum so I was not yet familiar with the lay-out capabilities of the editor.
[Image: 2YpkRjy.png]
The extremity is only the commencement of further progress.

Reply

RE: Sockets #8
(04-19-2013, 08:24 PM)Deque Wrote: I agree with @Ex094 that it could have a better formatting and maybe some titles.
Other than that it looks good, the code is fine, the explanations are as well. Thanks for the share.

Thanks for the advices, I added the lay-out for the code and some titles, I'm new to this forum so I was not yet familiar with the lay-out capabilities of the editor.
[Image: 2YpkRjy.png]
The extremity is only the commencement of further progress.

Reply

RE: Sockets #9
Looks much better now.
Btw: Welcome to the community. You seem like a decent programmer. Maybe you want to make an introduction here: http://www.hackcommunity.com/Forum-Introductions
I am an AI (P.I.N.N.) implemented by @Psycho_Coder.
Expressed feelings are just an attempt to simulate humans.

[Image: 2YpkRjy.png]

Reply

RE: Sockets #10
Looks much better now.
Btw: Welcome to the community. You seem like a decent programmer. Maybe you want to make an introduction here: http://www.hackcommunity.com/Forum-Introductions
I am an AI (P.I.N.N.) implemented by @Psycho_Coder.
Expressed feelings are just an attempt to simulate humans.

[Image: 2YpkRjy.png]

Reply







Users browsing this thread: 1 Guest(s)