Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package newpackage;
- import com.sun.deploy.util.SessionState;
- import java.io.IOException;
- import java.io.PrintStream;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Objects;
- import java.util.Scanner;
- public class Server {
- public Server() {
- clients = new ArrayList<>();
- lock = new Object();
- }
- public static void main(String[] args) throws IOException {
- Server server = new Server();
- server.start();
- }
- private List<PrintStream> clients;
- private final Object lock;
- public void start() throws IOException {
- try (ServerSocket serverSocket = new ServerSocket(2101)) {
- while (true) {
- Socket client = serverSocket.accept();
- Thread clientThread = new Thread(() -> {
- try {
- Scanner in = new Scanner(client.getInputStream());
- PrintStream out = new PrintStream(client.getOutputStream());
- synchronized (lock) {
- clients.add(out);
- }
- while (true) {
- String line = in.nextLine();
- if (line.contains("quit")) {
- synchronized (lock) {
- clients.remove(out);
- }
- return;
- }
- for (PrintStream c : clients)
- c.println(line);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- });
- clientThread.start();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- //////////////////////////////////////////////////////////////////////
- package newpackage;
- import java.io.IOException;
- import java.io.PrintStream;
- import java.net.Socket;
- import java.util.Scanner;
- public class Client {
- public static void main(String[] args) {
- Client client = new Client();
- client.start();
- }
- public void start() {
- try {
- Socket server = new Socket("localhost", 2101);
- Scanner in = new Scanner(server.getInputStream());
- PrintStream out = new PrintStream(server.getOutputStream());
- Thread readerThread = new Thread(() -> {
- while (true) {
- if (in.hasNextLine())
- System.out.println(in.nextLine());
- }
- });
- Thread writerThread = new Thread(() -> {
- Scanner console = new Scanner(System.in);
- String myName = console.nextLine();
- while (true) {
- String line = console.nextLine();
- out.println(myName + ": " + line);
- if (line.contains("quit")) {
- try {
- server.close();
- }
- catch (IOException e){
- e.printStackTrace();
- }
- return;
- }
- }
- });
- readerThread.start();
- writerThread.start();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement