Introduction to Socket Programming
In this lab, we are going to learn about the network socket programming in java. In particular, we are going to learn about how to work with TCP/IP, and how to work with HTTP, two common protocols that are part of network programming. We are going to start with using the HTTP protocol to work with URLs. Lets get started.
1. Using the HTTP protocol to parse a URL
Create a simple text file and name it UrlProg.java.
Open the UrlProg.java with a text editor, i.e. notepad, and write your codes, in the order provided, into this file.
To do network programming, we need to use the net set of classes, so:
Import java.net.*;
We are also going to do some import/output, so:
Import java.io.*;
First step is to throw an exception in case we face any problem while opening a connection.
Public class UrlProg {
Public static void main(string[] args) throws Exception {
This program will connect to a website and get some basic information about the website, and display all the content of the website in a character form.
A URL uniform resource locator is used to simply define the website we are willing to catch which should include the http://
URL theURL = new URL(http://www.dal.ca);
You can choose any website in this case.
Next we want to display the content of the website, in another word the raw html. To do that, we have to call openConnection method of theURL object:
URLConnection theConn = theURL.openConnection();
CSCI 3171 Network Computing February 4, 2015
CSCI 3171 Network Computing February 1 and 31,02, 0210717
Once we opened the connection, we want to check if there is content. To do so, we can check the length of the content.
int contentLen = theConn.getContentLength();
if (contentLen != 0) {
Now we are ready to display the content. We call a getInputStream object to read the characters as they come across our connection. We also have a while loop. While there are more content to read, the program reads the character and converts it to a char, until we are out of data to read. Then we close the input object.
InputStream urlInput = theConn.getInputStream();
while (((c = urlInput.read()) != -1))
{
System.out.print((char) c);
}
urlInput.close();
}
If there is no content, we run a message, sorry, no content:
System.out.println(Sorry, no content.);
We are done here. Your code should be like this:
Now save the program and compile it by javac and then run it by java, using command prompt window:
C:mywork> javac UrlProg.java
C:mywork> java UrlProg
You should see the program output. As you can see, we have lots of raw HTML to go through.
2. Echo Client/Server, using TCP/IP
In this section, we are going to develop an echo server and an echo client to demonstrate network programming using TCP/IP in java. The echo server will accept incoming messages, and the echo client will allow us to send the messages to the echo server. Lets get started developing the server first.
Create a simple text file and name it EchoServer.java. We begin by doing our import first:
import java.net.*;
import java.io.*;
First thing we do is to set up a server socket, we call it serverSock. We put it in the global area, because we are going to use it in two tries.
ServerSocket serverSock = null;
In the first try, we are going to instantiate the server socket by setting up a server socket on port 10007, which is just a random port to use, and of course our client also sends its messages to this random port.
try {
serverSock = new ServerSocket(10007);
}
In case the connection was unsuccessful:
catch (IOException ie) {
System.out.println(Cant listen on 10007);
System.exit(1);
}
Otherwise, we set a client socket, and print out a message that says we are listening for a connection. In other words, we are waiting for a client to connect to our server.
Socket clientSock = null;
System.out.println(Listening for connection.);
The code that accept the connection from the client is the accept method of our serverSocket object. Again we put that in a try catch, so if we are not able to connect successfully, we will write a message that says accept failed, and exit the program.
try {
clientSock = serverSock.accept();
}
catch (IOException ie) {
System.out.println(Accept failed.);
System.exit(1);
}
Otherwise, we write a message that says connection successful, and we write out another message saying we are listening for input. In other word, we are waiting for the client program to send us some output.
System.out.println(Connection successful.); System.out.println(Listening for input.);
If we get that output, then we should have an output object to accept it.
We also need to create a buffer reader object
We need a variable to store the input and then display it. The Program ends when it receives a Bye message.
String inputLine;
while ((inputLine = input.readLine()) != null) { System.out.println(Server: + inputLine); output.println(inputLine);
if (inputLine.equals(Bye)) {break;}
}
Finally we close all of our connections.
output.close();
input.close();
clientSock.close();
serverSock.close();
PrintWriter output = new
PrintWriter(clientSock.getOutputStream(), true);
BufferedReader input = new BufferedReader(new
InputStreamReader(clientSock.getInputStream()));
We are almost done. Your code should be like this:
Now save the program and compile it by javac and then run it by java, using command prompt window:
javac EchoServer.java
java EchoServer
As you can see, nothing will happen, because there is nothing to connect to the server. We still dont have a client to access it. Now we start writing the Echo Client to connect to the Echo Server.
Create a simple text file and name it EchoClient.java. Of course we write our imports first.
import java.io.*;
import java.net.*;
The first thing we are going to do is to create a socket object that we call it sock, and a print writer object that we call it output, and a buffer reader object that we call it input.
Socket sock = null;
PrintWriter output = null;
BufferedReader input = null;
Then the client has to create a socket, which uses the local machine IP address as the destination (127.0.0.1), and the port number that the server is looking for, which is 10007. Note that this IP address can be changed by any other IP addresses in your network, but if you are going to test both the client and the server programs on the same machine, you should use 127.0.0.1 as the destination IP address.
try {
sock = new Socket(127.0.0.1, 10 007);
Our output object is an output stream from the socket.
output = new PrintWriter(sock.getOutputStream(), true); Our input object also gets an input stream from the socket.
}
Now we are ready for our catches. If the local machine is not working for some reason, we get unknown host exception:
input = new BufferedReader(new
InputStreamReader(sock.getInputStream()));
catch (UnknownHostException e) {
System.out.println(Unknown host);
System.exit(1);
}
Now we create the second catch for any other exception, and displays we cannot connect.
catch (IOException ie) {
System.out.println(Cannot connect to host);
System.exit(1);
}
Next we need an input object to read from the standard input, so that the client can type something in.
And we need a string variable to get the user input.
String userInput;
Then we display the user input and then return the echo from the echo server.
while ((userInput = stdIn.readLine()) != null) {
output.println(userInput);
System.out.println(echo: + input.readLine());
}
Thats all the client does. Now we are ready to close everything.
output.close(); input.close(); stdIn.close(); sock.close();
Your code should be like this:
BufferedReader stdIn = new BufferedReader(new
InputStreamReader(System.in));
Now save the program and compile it by javac, using command prompt window:
javac EchoClient.java
Then run the echo server first from another command prompt window.
java EchoServer
And then run the echo client.
java EchoClient
Notice that, when we run the client, we get the connection successful message at the server. Now the server is listening for input. Type a message at the client input to the server. As you can see, the server receives it and echoes it back.
We saw how to use TCP/IP to connect two computers to send messages back and forth. With a little bit of extra work, you can easily build a chat system, so that the client could send its own messages and the server could also send its own messages. The ChatClient.java and ChatServer.java are provided, so that the server can chat with the client and the client can chat with the server. The difference between chat client/server and echo client/server is that the echo server/client was only one way communication. Only client could send messages to the server, and the server would echo them back to the client. In the chat client/server program, we can send messages in both ways. Notice that the ChatServer should run before running the ChatClient. Lots of modifications you can make to these programs such as receiving multiple connections from several clients simultaneously, so that multiple clients can connect and then multiple people can talk to each other. You can create a graphical user interface to make the program looks prettier.
Lab report
In this lab, you need to implement a client and a server code to interact with each other as follows:
The server listens on port: 9000
The client connects to the server and sends the hello message, Hello
If the server received the hello message, it responds with the message with the following pattern
YourName YourBannerID
, e.g., ALI B00111111
If the client receives the response correctly, the client closes the connection.
You need to submit the screenshots of the client terminal, server terminals, client code, and server code on the report.
Reviews
There are no reviews yet.