Jump to content


Photo

Servidore Socket


  • Faça o login para participar
1 reply to this topic

#1 nandonakahara

nandonakahara

    Turista

  • Usuários
  • 36 posts
  • Sexo:Não informado

Posted 07/12/2005, 23:09

Bom eu estou criando uma aplicação em flash q se conecta a um servidor por tcp/ip enviando mensagens formatadas em xml, o caso eh q procurei por servidores e a melhor opção foi em java. Consegui um exemplo basico com o servidor do moock q funcionou bem, porem, não consigo seguir adiante com minha aplicação pois o servidor está com funções basica.
Como eu desconheço qs q totalmente a linguagem java gostaria q alguem fizesse umas pequenas modificações, que são bem simples mas como sou noob nessa area preciso de ajuda.

o q existe:

- qnd um usuario conecta ele adiciona o usuario a uma lista(NUMUSERS) e conta qnts existem
- qnd um usuario envia uma mensagem o servidor recebe e a envia de volta a tds os usuarios
- qnd um usuario desconecta ou perde a conexão o servidor envia a quantidade de usuarios (NUMUSERS) atual

As modificações:
- gostaria q em vez do usuario ser adicionado a lista como mais 1, existisse uma array e q qnd conectado ele fosse adicionado pelo nick ou um id a essa lista e enviasse a lista ao novo usuario e aos outros o novo nick/id

- qnd um usuario desconecta ou perde a conexão o servidor envia o nick/id do usuario desconectado

o codigo:

import java.awt.event.*;
import java.util.*;
import java.awt.*;
import java.io.*;
import java.net.*;

/**
 *
 * CommServer
 * <BR><BR>
 * Generic Flash Communication Server.  All communications sent and received
 * are (must be) terminated with a null character ('\0') consistent with
 * the way Flash does socket communications.  Any client which uses this
 * protocol should also work.
 * <BR><BR>
 * The server accepts messages from connected clients and broadcasts (verbatim)
 * those messages to all connected clients.  When clients connect or disconnect
 * the server also broadcasts the number of clients via a NUMCLIENTS tag.
 *
 * Usage: java CommServer [port]
 *
 * @author  Derek Clayton   derek_clayton@iceinc.com
 * @version 1.0.1
 */

public class CommServer {
    private Vector clients = new Vector();  // a list of all connected clients
    ServerSocket server;                    // the server
    
    /**
     * Constructor for the CommServer.  Begins the start server process.
     * @param   port   Port number the server should listen to for connections.
    */
    public CommServer(int port) {
        startServer(port);
    }

    /**
     * Starts the server and listens for connections.
     * @param   port   Port number the server should listen to for connections.
    */
    private void startServer(int port) {
        writeActivity("Attempting to Start Server");
        
        try {
            // --- create a new server 
            server = new ServerSocket(port);
            writeActivity("Server Started on Port: " + port);
            // --- while the server is active...
            while(true) {
                // --- ...listen for new client connections
                Socket socket = server.accept();
                CSClient client += new CSClient(this, socket);
                writeActivity(client.getIP() + " connected to the server.");
                // --- add the new client to our client list 
                clients.addElement(client);
                // --- start the client thread
                client.start();  
                // --- broadcast the new number of clients
                broadcastMessage("<NUMCLIENTS>" + clients.size()
                               + "</NUMCLIENTS>");
            }
        } catch(IOException ioe) {
            writeActivity("Server Error...Stopping Server");
            // kill this server
            killServer();
        } 
    }

    /**
     * Broadcasts a message too all connected clients.  Messages are terminated
     * with a null character.
     * @param   message    The message to broadcast.
    */
    public synchronized void broadcastMessage(String message) {
        // --- add the null character to the message
        message += '\0';
        
        // --- enumerate through the clients and send each the message
        Enumeration enum = clients.elements();
        while (enum.hasMoreElements()) {
            CSClient client = (CSClient)enum.nextElement();
            client.send(message);
        }

    }

    /**
     * Removes clients from the client list.
     * @param   client    The CSClient to remove.
    */
    public void removeClient(CSClient client) {
        writeActivity(client.getIP() + " has left the server.");
        
        // --- remove the client from the list
        clients.removeElement(client);
        
        // --- broadcast the new number of clients
        broadcastMessage("<NUMCLIENTS>" + clients.size() + "</NUMCLIENTS>");
    }

    /**
     * Writes a message to System.out.println in the format
     * [mm/dd/yy hh:mm:ss] message.
     * @param   activity    The message.
    */
    public void writeActivity(String activity) {
        // --- get the current date and time
        Calendar cal = Calendar.getInstance();
        activity = "[" + cal.get(Calendar.MONTH) 
                 + "/" + cal.get(Calendar.DAY_OF_MONTH) 
                 + "/" + cal.get(Calendar.YEAR) 
                 + " " 
                 + cal.get(Calendar.HOUR_OF_DAY) 
                 + ":" + cal.get(Calendar.MINUTE) 
                 + ":" + cal.get(Calendar.SECOND) 
                 + "] " + activity + "\n";

        // --- display the activity
        System.out.print(activity);
    }

    /**
     * Stops the server.
    */
    private void killServer() {
        try {
            // --- stop the server
            server.close();
            writeActivity("Server Stopped");
        } catch (IOException ioe) {
            writeActivity("Error while stopping Server");
        }
    }
    
    public static void main(String args[]) {
        // --- if correct number of arguments
        if(args.length == 1) {
            CommServer myCS = new CommServer(Integer.parseInt(args[0]));
        } else {
        // otherwise give correct usage
            System.out.println("Usage: java CommServer [port]");
        }
    }
}

grato desde jah

Fernando Nakahara

#2 Agente Linhares

Agente Linhares

    fuis...abraços!

  • Ex-Admins
  • 3138 posts
  • Sexo:Não informado
  • Localidade:Biritiba Mirim-SP

Posted 28/12/2005, 08:44

tenta achar alguns scripts prontos pra dar uma estudado como sao feitos..

aqui tem alguns sites:
http://forum.wmonlin...howtopic=101853
> Busca On-line - A Busca que faltava na Internet! - Cadastre-se!
---------------------------------------------------------------------------
> BRdesign.NET - Soluções em Websites e Sistemas E-Commerce.
---------------------------------------------------------------------------
> BR-ecommerce - Sua loja virtual na internet! - Apenas R$99,90 mensais (hospedagem inclusa)!




0 user(s) are reading this topic

0 membro(s), 0 visitante(s) e 0 membros anônimo(s)

IPB Skin By Virteq