You are on page 1of 2

ServerA.

java

import java.io.IOException;

public class ServerA {


private ServerSocket server;
private int port = 7777;

public ServerA() {
try {
server = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {


ServerA example = new ServerA();
example.handleConnection();
}

public void handleConnection() {


System.out.println("Waiting for client message...");

//
// tao vong lap de cho su ket noi tu client toi server
//
//
while (true) {
try {
Socket socket = server.accept();
new ConnectionHandler(socket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

class ConnectionHandler implements Runnable {


private Socket socket;

public ConnectionHandler(Socket socket) {


this.socket = socket;

Thread t = new Thread(this);


t.start();
}

public void run() {


try
{
//
// doc message duoc gui tu client
//
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);

Page 1
ServerA.java

//
// gui thong tin phan hoi toi client
//
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Hi...");

ois.close();
oos.close();
socket.close();

System.out.println("Waiting for client message...");


} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

Page 2

You might also like