Creating a socket server and socket client is easy as below.
Server
Server
import java.net.*;
import java.io.*;
public class KnockKnockServer
{
public static void main (String a[])
{
int portNumber = Integer.parseInt(a[0]);
try
{
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
// Initiate conversation with client
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
Client
Client is pretty simple as well, just give the hostname and the ip at which the server listens.
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket kkSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(kkSocket.getInputStream()));
)
references:
http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html
No comments:
Post a Comment