Skip to content
Snippets Groups Projects
Commit ebfacf30 authored by Brutzman, Don's avatar Brutzman, Don
Browse files

TcpExample4

parent e3f86e5a
No related branches found
No related tags found
No related merge requests found
package TcpExamples;
import java.io.*;
import java.net.*;
//import java.time.LocalTime; // conversion?
/**
* This is a slightly different client. It establishes a connection
* to the server, then checks how long it takes to read the single
* line it expects.
*
* @author mcgredo
*/
public class TcpExample4Client
{
public static void main(String[] args)
{
try
{
System.out.println("TcpExample4Client start");
System.out.println("==================================================");
for (int loopCount=1; loopCount <= 4; loopCount++) // loop 4 times
{
System.out.println("TcpExample4Client creating socket #" + loopCount + "...");
// We request an IP to connect to ("localhost") and
// port number at that IP (2317). This establishes
// a connection to that IP in the form of the Socket
// object; the server uses a ServerSocket to wait for
// connections.This particualar example is interacting
// with what it expects is a server that writes a single text
// line after 10 sec.
long startTime = System.currentTimeMillis();
Socket socket = new Socket("localhost", 2317);
// Read the single line written by the server. We'd
// do things a bit differently if many lines to be read
// from the server, instead of one only.
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String serverMessage = br.readLine();
long readTime = System.currentTimeMillis();
long timeLength = readTime - startTime;
System.out.println("TcpExample4Client: message received from server=" + serverMessage);
System.out.println("TcpExample4Client: time msec required for read=" + timeLength);
System.out.println("==================================================");
// To push this further, launch multiple copies of TcpExample4Client simultaneously
}
System.out.println("TcpExample4Client complete");
}
catch(IOException e)
{
System.out.println("Problem with TcpExample4Client, see exception trace:");
System.out.println(e);
}
}
}
\ No newline at end of file
package TcpExamples;
import java.io.*;
import java.net.*;
/**
* Handles all the logic associated with one connection
* by running in a thread of its own. This is the server
* portion as well, so we artifically invent what happens
* if the server can't respond to a connection for 10 sec.
*
* @author Don McGregor
*/
public class TcpExample4HandlerThread extends Thread
{
/** The socket connection to a client */
Socket socket;
/** The thread constructor creates the socket from
* a ServerSocket, and passes one to the thread
* responsible for handling the connection.
*
* @param socket The socket connection handled by this thread
*/
public TcpExample4HandlerThread(Socket socket)
{
this.socket = socket;
}
/** Handles one connection. We add an artificial slowness
* to handling the connection with a sleep(). This means
* the client won't see a server connection response for ten seconds (default).
*/
// @overriding run() method in Java Thread class is deliberate
@Override
public void run()
{
try
{
System.out.println("TcpExample4HandlerThread starting to handle a thread...");
// get the connection output stream, then wait a period of time.
OutputStream os = socket.getOutputStream();
PrintStream ps = new PrintStream(os);
final long TIMEOUT = 10000; // 10000 milliseconds = 10 seconds
System.out.println("TcpExample4HandlerThread pausing for TIMEOUT=" + TIMEOUT + "ms"); // debug
Thread.sleep(TIMEOUT); // 10 seconds
ps.println("This was written by the server TcpExample4HandlerThread");
ps.flush();
socket.close();
System.out.println("TcpExample4HandlerThread finished handling a thread, now exit.");
}
catch(IOException | InterruptedException e) // either a networking or a threading problem
{
System.out.println("Problem with TcpExample4HandlerThread, see exception trace:");
System.out.println(e);
}
}
}
Invocation instructions:
* run/debug TcpExample4ThreadServer.java
* don't run TcpExample4HandlerThread since it is launched as needed
* run/debug TcpExample4Client.java
Program responses:
===================================================
run:
TcpExample4ThreadServer ready to accept socket connections...
=============================================================
TcpExample4ThreadServer.handlerThread invocation for connection #1...
TcpExample4ThreadServer.handlerThread is launched, awaiting another connection...
TcpExample4HandlerThread starting to handle a thread...
TcpExample4HandlerThread pausing for TIMEOUT=10000ms
TcpExample4HandlerThread finished handling a thread, now exit.
=============================================================
TcpExample4ThreadServer.handlerThread invocation for connection #2...
TcpExample4ThreadServer.handlerThread is launched, awaiting another connection...
TcpExample4HandlerThread starting to handle a thread...
TcpExample4HandlerThread pausing for TIMEOUT=10000ms
TcpExample4HandlerThread finished handling a thread, now exit.
=============================================================
TcpExample4ThreadServer.handlerThread invocation for connection #3...
TcpExample4ThreadServer.handlerThread is launched, awaiting another connection...
TcpExample4HandlerThread starting to handle a thread...
TcpExample4HandlerThread pausing for TIMEOUT=10000ms
TcpExample4HandlerThread finished handling a thread, now exit.
=============================================================
TcpExample4ThreadServer.handlerThread invocation for connection #4...
TcpExample4ThreadServer.handlerThread is launched, awaiting another connection...
TcpExample4HandlerThread starting to handle a thread...
TcpExample4HandlerThread pausing for TIMEOUT=10000ms
TcpExample4HandlerThread finished handling a thread, now exit.
BUILD STOPPED (total time: 1 minute 7 seconds)
===================================================
run:
TcpExample4Client start
==================================================
TcpExample4Client creating socket #1...
TcpExample4Client: message received from server=This was written by the server TcpExample4HandlerThread
TcpExample4Client: time msec required for read=10021
==================================================
TcpExample4Client creating socket #2...
TcpExample4Client: message received from server=This was written by the server TcpExample4HandlerThread
TcpExample4Client: time msec required for read=10002
==================================================
TcpExample4Client creating socket #3...
TcpExample4Client: message received from server=This was written by the server TcpExample4HandlerThread
TcpExample4Client: time msec required for read=10001
==================================================
TcpExample4Client creating socket #4...
TcpExample4Client: message received from server=This was written by the server TcpExample4HandlerThread
TcpExample4Client: time msec required for read=10003
==================================================
TcpExample4Client complete
BUILD SUCCESSFUL (total time: 40 seconds)
package TcpExamples;
import java.io.IOException;
import java.net.*;
/**
* An example of using threads to handle multiple connections
* at the same time.
*
* @author mcgredo
*/
public class TcpExample4ThreadServer {
public static void main(String[] args) // execution starts here
{
try
{
ServerSocket serverSocket = new ServerSocket(2317);
int connectionCount = 0; // state variable
System.out.println("TcpExample4ThreadServer ready to accept socket connections...");
while(true) // infinite loop
{
Socket clientConnection = serverSocket.accept(); // block until connected
connectionCount++; // unblocked, got another connection
System.out.println("=============================================================");
System.out.println("TcpExample4ThreadServer.handlerThread invocation for connection #" + connectionCount + "...");
TcpExample4HandlerThread handlerThread = new TcpExample4HandlerThread(clientConnection);
handlerThread.start(); // invokes the run() method in that object
System.out.println("TcpExample4ThreadServer.handlerThread is launched, awaiting another connection...");
}
}
catch(IOException e)
{
System.out.println("Problem with TcpExample4ThreadServer, see exception trace:");
System.out.println("Error: " + e);
}
System.out.println("=============================================================");
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment