Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package f2015.ex3;
- import java.io.*;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.HashMap;
- import java.util.Map;
- public class Server {
- public static void main(String[] args) {
- try {
- Map<String, String> mp = new HashMap<>();
- ServerSocket ss = new ServerSocket(8080);
- while (true) {
- Socket s = ss.accept();
- System.out.println("New Connection!");
- new worker(s, mp).start();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- private static class worker extends Thread {
- private PrintWriter pw;
- private BufferedReader br;
- private Map<String, String> mp;
- worker(Socket s, Map<String, String> mp) {
- try {
- InputStream is = s.getInputStream();
- InputStreamReader isr = new InputStreamReader(is);
- br = new BufferedReader(isr);
- OutputStream os = s.getOutputStream();
- pw = new PrintWriter(os, true);
- this.mp = mp;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void run() {
- while (true) {
- try {
- String line = br.readLine();
- System.out.println("New Request : " + line);
- if (line.contains(":"))
- change_status(line);
- else
- send_status(line);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- private void change_status(String line) {
- int ind = line.indexOf(":");
- String name = line.substring(0, ind);
- String status = line.substring(ind + 1);
- synchronized (mp) {
- mp.put(name, status);
- }
- }
- private void send_status(String line) {
- String status;
- synchronized (mp) {
- status = mp.get(line);
- }
- this.pw.println(status);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement