Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Server.java*/
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- import java.net.ServerSocket;
- import java.util.Vector;
- public class Server extends Thread{
- private Socket socket;
- private static Vector<PrintWriter> writers = new Vector<PrintWriter>();
- public Server(Socket socket) {
- this.socket = socket;
- }
- public void run() {
- try {
- BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
- out.println("SUBMITNAME");
- String name = in.readLine();
- System.out.println(name+" joined");
- writers.add(out);
- while (true) {
- String input = in.readLine();
- for (PrintWriter writer : writers)
- writer.println("MESSAGE " + name + ": " + input);
- }
- } catch (Exception e) {System.err.println(e);}
- }
- public static void main(String[] args) throws Exception {
- ServerSocket serversocket = new ServerSocket(9001);
- System.out.println("The server is running at port 9001.");
- while (true)
- new Server(serversocket.accept()).start();
- }
- }
- /*Client.java*/
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- import java.util.Scanner;
- public class Client {
- public static void main(String[] args) throws Exception {
- Scanner sc = new Scanner(System.in);
- Socket socket = new Socket("localhost", 9001);
- BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
- System.out.print("Enter your name: ");
- String name = sc.nextLine();
- while (true) {
- String line = in.readLine();
- if (line.startsWith("SUBMITNAME")) out.println(name);
- else if (line.startsWith("MESSAGE"))
- System.out.println(line.substring(8));
- if(name.startsWith("master")){
- System.out.print("Enter a message: ");
- out.println(sc.nextLine());
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement