CSSoldier back again with a new post to help the fellow coders. Today we have some simple java code for a TCP connection. For those that do not know, TCP stands for Transmission Control Protocol. TCP is the most widely used protocol for transferring packets of information across the internet. TCP is a reliable connection protocol that provides ordered and error-checked delivery of information. Needless to say, it is pretty damn important. More information on TCP can be found here: https://en.wikipedia.org/wiki/Transmission_Control_Protocol
This works by way of a Client-Server Architecture. We initiate a point-to-point client-server connection using this Transmission Control Protocol. TCP guarantees the delivery of the data it transmits in the form of "packets". If packets are lost or damaged, TCP will resend the data until it verifies that packets have been successfully transmitted. This is important when you want to make sure your "I love you" message correctly makes it to your loved one....before they think you no longer care and you end up in the dog house. Anyway, moving on...
When establishing connectivity, the client and server each bind a "socket" to their end of the connection. Once a connection has been established, the client and server both read from, and write to, the socket when communicating. Its like picking up the phone, dialing a number and waiting for the connection, when the person picks up, you each listen for the other's communication. You can think of this two way communication with reliability checks like this: As one person talks, the other person will acknowledge what he/she says by saying "ok", "uh huh", "sure", or "I hear ya". If someone cuts out while saying something, you may say something like "I'm sorry, I didn't catch that last bit." Then the person will re-say what they previously said.
Java uses the SeverSocket and Socket classes from the java.net library to accomplish this combination of "IPaddress and port number".
Here is a summary of the Client-Server Architecture:
1. Create a Socket or ServerSocket object and open it over a specified port and IP address or host name.
2. Instantiate InputStreamReader, BufferedReader, and PrintStream objects to stream data to and from each socket. (its like a chaining together of objects)
3. Read from and Write to the stream between the sockets using their agreed-upon protocol.
4. Close the input and output streams.
5. Close the Socket or ServerSocket Objects.
Here is an Illustration:
This code repository can be found on github here: https://github.com/GettinDatFoShow/javaAppLearning.git
Hope you enjoyed today's information and it helps you in your Computer Science or IT learning.
Have a great day and remember, #SudoAptGetUpdateYourBrain
resource used: https://www.youtube.com/watch?v=6G_W54zuadg
Here is each class: (remember that the server socket code must be ran first, obviously)
ServerSock.java:___________________________________________________________
/*
* This is a Server Socket listening on port 1776 (I call it the freedom port)
* Once a connection is heard from a client, a socket opened and accepted.
* from the socket instance that is created, there are a few properties available.
* The .getInetAdress() from the socket returns an InetAddress instance of the client on the
* other side of the socket. we can then call the .getHostAddress on the InetAddress object
* and obtain a string of the clients IPaddress.
* Then, an InputStreamReader object is created using the socket as its parameter.
* After this, a BufferedReader object is created using the InputStreamReader object as the parameter.
* The socket is now ready listen for messages sent through the socket from the client.
* there is a while loop once the readline() function is called appon the bufferedReader object
* becuase the readline() will stop at the \n character. If it doesnt keep looping it will not be
* able to read out multiple lines from the client.
* Once the client connects the server sends a message back with its connecting IPaddress,
* alonge with the date. Then sends and empty string (which will have a '/n' character appended,
* so that the client will then close the socket (this is purely for demo purposes and is may not be needed).
*/
package tcpdemo;
import java.io.*;
import java.net.*;
import java.util.Date;
/**
*
* @author Robert Morris
*/
public class ServerSock {
public static void main(String[] args) throws Exception{
ServerSock Server = new ServerSock();
Server.run();
}
public void run() throws Exception{
String messageIn = null;
ServerSocket serverSocket = new ServerSocket(1776);
Socket socket = serverSocket.accept();
// Information Regarding the Connection.
InetAddress INA = socket.getInetAddress();
String hostIP = INA.getHostAddress();
Date date = new Date();
InputStreamReader inRead = new InputStreamReader(socket.getInputStream());
BufferedReader bRead = new BufferedReader(inRead);
while (( messageIn = bRead.readLine()) != null){
if (messageIn.length() <= 2){
break;
}
System.out.println(messageIn);
String messageOut = "Your IP address is: "+ hostIP + "\n"
+ "It is now: " + date;
PrintStream pStream = new PrintStream(socket.getOutputStream());
pStream.println(messageOut);
pStream.println("");
break;
}
socket.close();
}
}
// ***** end SeverSock.java *****
_________________________________________________________________________
ClientSock.java:___________________________________________________________
/*
*This is a client socket class that connects to the server socket
* on a pre-specified of 1776, supplying a name of 'localhost'
* once the socket is accepted by the server a PrintStream object is created with
* the socket.getOutputStream() as a parameter, following this creation, a message is sent
* to the server.
* Then, an InputStreamReader object is created using the socket as its parameter.
* After this, a BufferedReader object is created using the InputStreamReader object as the parameter.
* The socket is now ready listen for messages sent through the socket from the client.
* there is a while loop once the readline() function is called appon the bufferedReader object
* becuase the readline() will stop at the \n character. If it doesnt keep looping it will not be
* able to read out multiple lines from the server.
* a while loop is created for the bufferedReader to be able to read multiple lines so that
* it does not terminate until a specified message is received. In this case the specified message is
* a 'new line' character.
*/
package tcpdemo;
import java.io.*;
import java.net.*;
/**
*
* @author Robert Morris
*/// ***** end ClientSock.java *****// ***** end ClientSock.java *****
public class ClientSock {
public static void main(String [] args) throws Exception{
ClientSock client = new ClientSock();
client.run();
}
public void run() throws Exception{
String messageIn = null;
Socket socket = new Socket("localhost", 1776);
PrintStream pStream = new PrintStream(socket.getOutputStream());
pStream.println("I NEED TO CONNECT NOWWWWW!!!!");
InputStreamReader inRead = new InputStreamReader(socket.getInputStream());
BufferedReader bRead = new BufferedReader(inRead);
while((messageIn = bRead.readLine()) != null){
if (messageIn.length() <= 2){
break;
}
System.out.println(messageIn);
}
socket.close();
}
}
No comments:
Post a Comment