Socket Programming: Using Java
Socket Programming: Using Java
Using Java
ICS-432
Muhammad Wasiq
Introduction to Sockets
SYN Server
Client
SYN/ACK
ACK
PUSH
ACK
Introduction to Sockets
Creating a Client Socket
import java.io.*;
import java.net.*;
try {
//create a client socket
socket = new Socket("localhost", 4444);
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
}
}
Introduction to Sockets
Creating a Server Socket
import java.io.*;
import java.net.*;
public class CreateServerSocket {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket=null;
Socket clientSocket = null;
String inputLine, outputLine;
try {
//creating a server socket
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
System.exit(-1);
}
try {
//accepting a clients request
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
}
Introduction to Sockets
Exercise # 1
Compile the CreateServerSocket and
CreateClientSocket classes and run them.
Analyze the traffic using ethereal when you run
them.
Introduction to Sockets
Exchanging Data Between Client & Server
Sending message to server from client and
receiving replies from the server
// Create a print writer to writing to the socket. In other words, to send data to
// server
out = new PrintWriter(socket.getOutputStream(), true);
// Create an input stream to read data from the socket. In other words, to
// receive data from server
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Create an input stream to read data from the socket. In other words, to
// receive data from client
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
On Client Side:
// Closing the input stream
in.close();
while (listening) {
new EchoServerThread(serverSocket.accept()).start();
}
Introduction to Sockets
A Persistent Server (A multi-threaded Server)
Download EchoClient.java, EchoServer.java and
EchoServerThread.java from
http://www.ccse.kfupm.edu.sa/wasiq/ics432.
Investigate their code, compile them and run them.
Analyze the traffic being exchanged between them using
Ethereal.
Introduction to Sockets
A Simple SMTP Client
You can use the following four basic SMTP commands to
write a simple SMTP client:
HELO smtp
MAIL FROM: <emailid@domainname>
RCPT TO: <emailid@domainname>
DATA
Following the data command, you type your e-mail text
End your e-mail content by issuing <CRLF>.<CRLF> command
In programs, you can replace CRLF by \n
QUIT