Imas srece, bas sad radim na client server chatu, ali za Android. Nema veze, evo ti server, u svojim korenima.
Server.java
Code:
package com.chat;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server
{
// The ServerSocket we'll use for accepting new connections
private ServerSocket ss;
//server port
private static int _port = 7475;
// A mapping from sockets to DataOutputStreams. This will
// help us avoid having to create a DataOutputStream each time
// we want to write to a stream.
private Hashtable<Socket, DataOutputStream> outputStreams = new Hashtable<Socket, DataOutputStream>();
// Constructor and while-accept loop all in one.
public Server( int port ) throws IOException {
// All we have to do is listen
listOfClients= new Vector<ServerThread>();
listen( port );
}
//all clients in a vector
private Vector<ServerThread> listOfClients;
/*Checks if nickname is avaliable*/
public boolean checkNick(String nick)
{
if(nick.contains("#"))
return false;
for (Enumeration<ServerThread> e = listOfClients.elements(); e.hasMoreElements(); ) {
if ( nick.equals( e.nextElement().getNick() )) {
return false;
}
}
return true;
}
public void removeClient(ServerThread temp){listOfClients.remove(temp);}
private void listen( int port ) throws IOException {
// Create the ServerSocket
ss = new ServerSocket( port );
// Tell the world we're ready to go
System.out.println( "Listening on "+ss );
// Keep accepting connections forever
while (true) {
// Grab the next incoming connection
Socket s = ss.accept();
// Tell the world we've got it
System.out.println( "Connection from "+s );
// Create a DataOutputStream for writing data to the client
DataOutputStream dout = new DataOutputStream( s.getOutputStream() );
// Save this stream so we don't need to make it again
outputStreams.put( s, dout );
// Create a new thread for this connection, and then forget
// about it
ServerThread current = new ServerThread( this, s );
current.setDout(dout);
listOfClients.add(current);
current.start();
}
}
// Get an enumeration of all the OutputStreams, one for each client
// connected to us
Enumeration<DataOutputStream> getOutputStreams() {
return outputStreams.elements();
}
// Send a message to all clients (utility routine)
void sendToAll( String message ) {
// We synchronize on this because another thread might be
// calling removeConnection() and this would screw us up
// as we tried to walk through the list
synchronized( outputStreams ) {
// For each client ...
for (Enumeration<DataOutputStream> e = getOutputStreams(); e.hasMoreElements(); ) {
// ... get the output stream ...
DataOutputStream dout = (DataOutputStream)e.nextElement();
// ... and send the message
try {
dout.writeUTF( message );
} catch( IOException ie ) { System.out.println( ie ); }
}
}
}
// Remove a socket, and it's corresponding output stream, from our
// list. This is usually called by a connection thread that has
// discovered that the connecting to the client is dead.
void removeConnection( Socket s ) {
// Synchronize so we don't mess up sendToAll() while it walks
// down the list of all output streams
synchronized( outputStreams ) {
// Tell the world
System.out.println( "Removing connection to "+s );
// Remove it from our hashtable/list
outputStreams.remove( s );
// Make sure it's closed
try {
s.close();
} catch( IOException ie ) {
System.out.println( "Error closing "+s );
ie.printStackTrace();
}
}
}
// Main routine
static public void main( String args[] ) throws Exception {
// Create a Server object, which will automatically begin
// accepting connections.
new Server( _port );
}
}
ServerThread.java
Code:
package com.chat;
import java.io.*;
import java.net.*;
public class ServerThread extends Thread {
//The Server that spawned us
private Server server;
//Client socket
private Socket socket;
//Client info
private String nick;
private DataOutputStream dout;
public ServerThread(Server _server, Socket _socket) {
this.server = _server;
this.socket = _socket;
}
public String getNick(){ return nick; }
public void setDout(DataOutputStream _dout){dout=_dout;}
public void run()
{
try {
// Create a DataInputStream for communication; the client
// is using a DataOutputStream to write to us
DataInputStream din = new DataInputStream( socket.getInputStream() );
String _nick = din.readUTF();
System.out.println(socket.toString()+ " : Received nickname: "+ _nick);
//Until we get a valid nick
while( ! server.checkNick(_nick) )
{
System.out.println(socket.toString()+ " : Nickname in use");
dout.writeUTF("#inuse");
//Wait for reply with new nick
_nick = din.readUTF();
}
nick = _nick;
//report to client that nick is ok
dout.writeUTF("#ok");
// Over and over, read message and send it to all clients
while (true) {
// ... read the next message ...
String message = din.readUTF();
// ... tell the world ...
System.out.println( "Sending "+message );
// ... and have the server send it to all clients
server.sendToAll("#"+nick+"##"+ message );
}
} catch( EOFException ie ) {
// This doesn't need an error message
} catch( IOException ie ) {
// This does; tell the world!
ie.printStackTrace();
} finally {
server.removeClient(this);
server.removeConnection( socket );
}
}
}
Sto se tice clienta, dacu ti samo ti neke elemente iz moje Android aplikacije koji ti mozda tebaju. U supstinim moras da imas jednu nit u pozadini koja ce da radi ovako nesto
Code:
mySock = new Socket(Main.hostAddress, Main.port);
OutputStream sou = mySock.getOutputStream();
dos = new DataOutputStream(sou);
dis = new DataInputStream( mySock.getInputStream() );
try {
while (work)
{
LastMessage=dis.readUTF();
handler.sendEmptyMessage(1);// Ovo ti je u Androidu signalizilas handler klasi koji reaguje na event( poruku) i osvezava UI.
}
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
Sad, ja iz moje User interface niti, citam poruke i saljem ih sa dos.WriteUTF(Message);
Ti vidi kako ces to da resis, da li ces u konzoli ili ipak neki swing interface..
Inace server i nije nesto efikasan posto za svakog clienta pravi po jednu nit, ako aplikacija naraste onda cu da predjem na selektore, ovako je za sada samo neki test. Server ima funkciju za proveravanje nicka, on ocekuje da je prva poruka koju client posalje u stvari nickname. To sve mozes da obrises.
Nadam se da ce ti ovo pomoci.