Skip to content

Instantly share code, notes, and snippets.

@szainmehdi
Forked from anonymous/Client.java
Last active August 29, 2015 14:01
Show Gist options
  • Save szainmehdi/459eee5a7de58724e61d to your computer and use it in GitHub Desktop.
Save szainmehdi/459eee5a7de58724e61d to your computer and use it in GitHub Desktop.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.Socket;
public class Client
{
private static final int USER_THROTTLE = 200;
private Socket socket;
private boolean connected;
private Inport inport;
private class Inport extends Thread
{
private InputStream in;
private BufferedReader reader;
public void run() {
System.err.println("Running Inport");
// Try to connect to the socket and obtain the input stream.
try {
in = socket.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
} catch(IOException e) {
System.out.println("Could not get input stream from "+toString());
return;
}
System.out.println(socket+" has connected input.");
// Loop infinitely until interrupted.
while(true) {
// System.err.println("Looping...");
try {
while(reader.ready()) {
System.out.println(reader.readLine());
}
Thread.sleep(USER_THROTTLE);
} catch(Exception e) {
System.out.println(toString()+" has input interrupted.");
}
}
}
}
public Client(Socket newSocket) {
// Assign the new socket
socket = newSocket;
// Set the connection status as connected.
connected = true;
// Create a new Inport and start it.
inport = new Inport();
inport.start();
}
/**
*
* Determine connection status.
*
* @return true|false
*/
public boolean isConnected() {
return connected;
}
/**
*
* Close the connection to the socket.
*
*/
public void purge() {
try {
connected = false;
socket.close();
} catch(IOException e) {
System.out.println("Could not purge "+socket+".");
}
}
public String toString() {
return new String(socket.toString());
}
}
import java.net.Socket;
public class Test {
public static void main(String[] args) throws Exception {
// Create a new client object.
String hostName = "10.51.103.43";
int port = 30480;
Socket socket = new Socket(hostName, port);
Client client = new Client(socket);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment