Socket Wie ein einfacher Multithreads Service mit Telnet als Client mit Observable/Observer gelöst....

azuccare

Mitglied
z.B. als Client: telnet 192.168.121.35 7777

untere code als ausführbare JAR-File erstellen

danach aufruf mit: java -jar ChattService.jar -p 7777

:oops:
Java:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;
import java.util.Scanner;




/**
 * @author Adriano Zuccarello
 *
 */


public class ChatThreadService extends Observable {
    
    private long nofThreads = 0;
    private SimpleDateFormat sdf;
    private int mPort = 7575;
    
    public ChatThreadService() {
        sdf = new SimpleDateFormat("HH:mm:ss");
    }
    public ChatThreadService(String[] pArgs) {
        this();
        mPort = setup(pArgs);
        System.out.println("Listen on Port: "+ mPort);
    }
    
    /**
     * setup
     * 
     * @param pArgs
     *      -p <port> [-n <name>] default: -n user.name
     */
    private int setup(String[] pArgs) {
        for (int i = 0; i < pArgs.length; i++) {
            if ((pArgs[i].endsWith("-p") && ((i + 1) < pArgs.length))) {
                try {
                    mPort = Integer.parseInt(pArgs[++i].trim());
                } catch (Exception e) {
                    System.err.printf("Bad format in  argument (%s)\nWill use Port: %i",    pArgs[i], mPort);
                }
            }
        }


        if (mPort <= 0)  {
            System.err.println("Port has to be defined greater 0"); 
        }
        
        System.out.println("Setup: Port: "+ mPort);
        return mPort;
    }
    
    public void start() {
        try {
            Socket incomingSocket = null;
            ServerSocket serviceSocket = new ServerSocket(mPort);
            
            try {
                while( (incomingSocket = serviceSocket.accept()) != null) {
                    System.out.println("Start Thread"+ ++nofThreads);
                    
                    ClientThread threadClient = new ClientThread(incomingSocket, nofThreads);
                    
                    this.addObserver(threadClient);
                    
                    Thread thread = new Thread(threadClient);
                    thread.start();
                    
                    broadcast("Client-"+ nofThreads +" logged in");
                    
                    java.awt.Toolkit.getDefaultToolkit().beep();
                }
            }
            finally {
                serviceSocket.close();
            }
            
        } catch (IOException ioex) { 
            ioex.printStackTrace(); 
        }
    }
    
    private void removeObserver(ClientThread pCTh) {
        this.deleteObserver(pCTh);
        --nofThreads;
    }
    
    private synchronized void broadcast(String message) {
        // add HH:mm:ss and \n to the message
        this.setChanged();
        this.notifyObservers(sdf.format(new Date()) +" "+ message);
    }


    
    //Chat-Client Thread
    class ClientThread implements Runnable, Observer {
        private Socket mSocket;
        private long mCounter;
        private String mChatterName;
        
        ClientThread(final Socket pSocket, final long pCount) {
            this.mSocket = pSocket;
            this.mCounter = pCount;


            System.out.println("I am ChatClient-Number: "+ mCounter);
        }


        @Override
        public void run() {
            try {
                try {
                    mChatterName = mSocket.getInetAddress().getHostAddress() +" Chatter-"+ mCounter +": ";
                    
                    printMessage(mSocket.getOutputStream(), "Hello "+ mChatterName +"! Enter BYE to exit.\n", true);
                    
                    InputStream inStream = mSocket.getInputStream();
                    Scanner inScanner = new Scanner(inStream);
                    
                    boolean done = false;
                    while(!done && inScanner.hasNextLine()) {
                        String line = inScanner.nextLine();
                        done = line.trim().equalsIgnoreCase("BYE") ? true : false;
                        broadcast(mChatterName + line);
                        System.out.println(mChatterName + line);
                    }
                    
                    inScanner.close();
                }
                finally {
                    removeObserver(this);
                    mSocket.close();
                }
                
            } catch (IOException ioex) {
                ioex.printStackTrace();
            }
        }
        
        private void printMessage(final OutputStream os, final String msg, final boolean flush) {
            PrintWriter pwout = new PrintWriter(os, flush);
            pwout.println(msg);
            System.out.println(msg);
        }


        @Override
        public void update(Observable o, Object arg) {
            try {
                String observerArgs = (String)arg;
                if(observerArgs != null && mChatterName != null && !observerArgs.contains(mChatterName)) { /* don't show your self */
                    printMessage(mSocket.getOutputStream(), observerArgs, true);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }//End Chat-Client Thread






    public static void main(String[] args) {
        ChatThreadService thService = new ChatThreadService(args);
        thService.start();
    }


}
 

Anhänge

  • ChattServer.jar
    4,3 KB · Aufrufe: 5
  • ChatThreadService.java
    4,2 KB · Aufrufe: 6
Ähnliche Java Themen
  Titel Forum Antworten Datum
H Einfacher Server funktioniert nicht Netzwerkprogrammierung 1
B Einfacher Server mit Jetty Netzwerkprogrammierung 3
F RMI einfacher Chat - Callbacks(?) funktionieren nicht Netzwerkprogrammierung 7
D Apache CXF, JAX-WS Problem bei Arrays - einfacher Server Netzwerkprogrammierung 2
S Socket Einfacher filetransfer Netzwerkprogrammierung 10
B Einfacher Proxy Server Netzwerkprogrammierung 29
M Socket Probleme mit einfacher Socketverbindung Netzwerkprogrammierung 3
L einfacher server ohne threads Netzwerkprogrammierung 4
P Einfacher Server/Client Netzwerkprogrammierung 5
L Einfacher Proxy-Server Netzwerkprogrammierung 6
A einfacher Transfer mit Applets Netzwerkprogrammierung 4
C Einfacher Filedownload mit Sockets geht nicht für pdffiles Netzwerkprogrammierung 16
T Einfacher Servlet-Server Netzwerkprogrammierung 8
S Einfacher Multiuser chat in java Netzwerkprogrammierung 18
X Response eines RESTful-Service mit JSON Netzwerkprogrammierung 8
J Java Service Wrapper Netzwerkprogrammierung 1
M allgemeine Frage zu einem Web Service Client Netzwerkprogrammierung 2
C Socket Push Service realisieren? Netzwerkprogrammierung 6
1 JBoss Web Service Netzwerkprogrammierung 3
D Timer Service? Netzwerkprogrammierung 4
M RMI Service JBoss Netzwerkprogrammierung 3
G Buchinformationen aus dem Netz abrufen? Kostenloser Service? Netzwerkprogrammierung 3
S Threads bei Web Service sinnvoll oder Alternative? Netzwerkprogrammierung 2
R RMI: Remote Object ohne Naming Service benutzen? Netzwerkprogrammierung 2
C Web Service - Was muss ich lernen? Netzwerkprogrammierung 2
J Web Service mit legacy Wrapper Netzwerkprogrammierung 6

Ähnliche Java Themen

Neue Themen


Oben