Thread based Server
In this chapter you will learn:
Thread based ServerSocket
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
// j a v a 2 s.com
public class MainClass {
public static void main(String[] args) throws IOException {
int port = 9000;
ServerSocket server = new ServerSocket(port);
while (true) {
Socket socket = server.accept();
Thread stuffer = new StuffThread(socket);
stuffer.start();
}
}
}
class StuffThread extends Thread {
private byte[] data = new byte[255];
private Socket socket;
public StuffThread(Socket socket) {
for (int i = 0; i < data.length; i++)
data[i] = (byte) i;
this.socket = socket;
}
public void run() {
try {
OutputStream out = new BufferedOutputStream(socket.getOutputStream());
while (!socket.isClosed()) {
out.write(data);
}
socket.close();
} catch (Exception e) {
}
}
}
A multithreaded Socket Server
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
//from ja v a 2 s .c om
public class EchoServer {
public static void main(String[] args) throws Exception {
ServerSocket m_ServerSocket = new ServerSocket(12111);
int id = 0;
while (true) {
Socket clientSocket = m_ServerSocket.accept();
ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
cliThread.start();
}
}
}
class ClientServiceThread extends Thread {
Socket clientSocket;
int clientID = -1;
boolean running = true;
ClientServiceThread(Socket s, int i) {
clientSocket = s;
clientID = i;
}
public void run() {
System.out.println("Accepted Client : ID - " + clientID + " : Address - "
+ clientSocket.getInetAddress().getHostName());
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(
new OutputStreamWriter(clientSocket.getOutputStream()));
while (running) {
String clientCommand = in.readLine();
System.out.println("Client Says :" + clientCommand);
if (clientCommand.equalsIgnoreCase("quit")) {
running = false;
System.out.print("Stopping client thread for client : " + clientID);
} else {
out.println(clientCommand);
out.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Socket