In the following program, we will demonstrate, how a connection can be established between client and server using Transport Layer Protocol - TCP. This code is self-explanatory. Hence, first, you will learn to develop server-side applications. Then, you will learn to develop client-side applications.
TcpEchoServer.java
package net.tcp.echo;
import java.net.*;
import java.io.*;
public class TcpEchoServer {
private static final int BUFSIZE = 32;
public static void main(String[] args) throws IOException {
int serverPort = 1000;
ServerSocket serverSocket = new ServerSocket(serverPort);
int recvMsgSize;
byte[] receiveBuf = new byte[BUFSIZE];
while (true) {
Socket clientSocket = serverSocket.accept();
SocketAddress clientAddress = clientSocket.getRemoteSocketAddress();
System.out.println("Client at " + clientAddress);
InputStream in = clientSocket.getInputStream();
OutputStream out = clientSocket.getOutputStream();
while ((recvMsgSize = in.read(receiveBuf)) != -1) {
System.out.println("Received Data : " + receiveBuf.toString());
out.write(receiveBuf, 0, recvMsgSize);
}
clientSocket.close();
}
}
}
TcpEchoClient.java
package net.tcp.echo;
import java.net.Socket;
import java.net.SocketException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class TcpEchoClient {
public static void main(String[] args) throws IOException {
if ((args.length < 2) || (args.length > 3))
throw new IllegalArgumentException("Parameter(s): <Server> [<Port>] <Word>");
String serverIP = args[0];
byte[] data = args[2].getBytes();
int serverPort = (args.length == 3) ? Integer.parseInt(args[1]) : 7;
Socket socket = new Socket(serverIP, serverPort);
System.out.println("Connected to server... sending echo message");
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
out.write(data);
int totalBytesReceived = 0;
int bytesRcvd;
while (totalBytesReceived < data.length) {
if ((bytesRcvd = in.read(data, totalBytesReceived, data.length - totalBytesReceived)) == -1)
throw new SocketException("Connection closed prematurely");
totalBytesReceived += bytesRcvd;
}
System.out.println("Received: " + new String(data));
socket.close();
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.