Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.net.*;
- import java.util.*;
- public class ClientStarer {
- private int ID;
- private Socket socket;
- private DataOutputStream dos;
- private DataInputStream dis;
- //todo: init other required variables here
- ClientStarer(int id, String host, int port) throws IOException {
- this.ID = id;
- socket=new Socket(InetAddress.getByName(host),port);
- dis= new DataInputStream(socket.getInputStream());
- dos=new DataOutputStream(socket.getOutputStream());
- dos.writeInt(id);
- dos.flush();
- // todo: Connect to server and send client ID
- this.listen();
- // todo: Listen for incoming messages
- }
- // todo: Implement the sending message mechanism
- void sendMessage(int idReceiver, String message) throws IOException {
- dos.writeUTF(message+":"+idReceiver);
- dos.flush();
- }
- // todo: end communication - send END to server
- private void endCommunication() throws IOException {
- dos.writeUTF("END");
- dos.flush();
- }
- // todo: listen for icoming messages from the server.
- // It should start a separate thread to handle listening
- // and not block the execution
- // Should start a new ClientStarterWorkerThread
- private void listen() {
- new ClientStarterWorkerThread(this.ID,dis).start();
- }
- public static void main(String[] args) throws IOException, InterruptedException {
- //todo: Initialize and start 3 clients
- ClientStarer client1=new ClientStarer(1,"localhost",9876);
- ClientStarer client2=new ClientStarer(2,"localhost",9876);
- ClientStarer client3=new ClientStarer(3,"localhost",9876);
- // Simulate chat
- client1.sendMessage(2, "Hello from client 1");
- Thread.sleep(1000);
- client2.sendMessage(3, "Hello from client 2");
- Thread.sleep(1000);
- client1.sendMessage(3, "Hello from client 1");
- Thread.sleep(1000);
- client3.sendMessage(1, "Hello from client 3");
- Thread.sleep(1000);
- client3.sendMessage(2, "Hello from client 3");
- // Exit the chatroom
- client1.endCommunication();
- client2.endCommunication();
- client3.endCommunication();
- }
- }
- class ClientStarterWorkerThread extends Thread {
- private int ID;
- private DataInputStream inputStream;
- public ClientStarterWorkerThread(int clientID, DataInputStream inputStream) {
- this.ID = clientID;
- this.inputStream = inputStream;
- }
- @Override
- public void run() {
- String line;
- while (true)
- {
- try {
- line=inputStream.readUTF();
- if(line.equals("END"))
- break;
- else
- System.out.println(line);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement