|
Tips & Tricks |
|
The Server side application follows these steps
1. Create a server socket by which a server can accept connections from clients across a network.
ServerSocket ss = new ServerSocket(1004);
2. Use accept() method of ServerSocket to connect to a client. It returns Socket object. Add this client socket into arraylist.
Socket s = ss.accept();
ArrayList al2 = new ArrayList();
Al2.add(s);
3. After getting the client socket it creates a thread and make DataInputStream for this socket. Then it reads user name and add it to arraylist and this arraylist object is written in ObjectOutputStream of each client by using
iterator.
DataInputStream din1=new
DataInputStream(s.getInputStream)
ArrayList alname=new ArrayList();
alname.add(din1.readUTF());
Iterator i1=al2.iterator();
Socket st1;
while(i1.hasNext()){
st1=(Socket)i1.next();
dout1=new
DataOutputStream(st1.getOutputStream());
ObjectOutputStream obj=new
ObjectOutputStream(dout1);
obj.writeObject(alname);
}
4. After this it makes a new thread and makes one DataInputStream for reading the messages which is sent by the client and after reading the message it creates the DataOutputStream for each socket and writes this message in each client output stream through
iterator.
String str=din.readUTF();
Iterator i=al.iterator();
Socket st;
|
|
while(i.hasNext()){
st=(Socket)i.next();
dout=new
DataOutputStream(st.getOutputStream());
dout.writeUTF(str);
dout.flush();
}
5. If any client logs out then server receives
the client name. Server removes it from the
arraylist and sends this updated arraylist to all
clients.
sname=ddin.readUTF();
alname.remove(sname);
MyServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class MyServer{
ServerSocket ss;
Socket s;
ArrayList al=new ArrayList();
ArrayList al1=new ArrayList();
ArrayList al2=new ArrayList();
ArrayList alname=new ArrayList();
Socket s1,s2;
MyServer()throws IOException{
ss=new ServerSocket(1004); // create
server socket
while(true){
s=ss.accept(); //accept the client socket
s1=ss.accept();
s2=ss.accept();
al.add(s); // add the client socket in
arraylist
al1.add(s1);
al2.add(s2);
System.out.println(“Client is Connected”);
//new thread to maintain the list of user name
MyThread2 m=new
MyThread2(s2,al2,alname);
Thread t2=new Thread(m);
t2.start();
//new thread to receive and send message
MyThread r=new MyThread(s,al);
Thread t=new Thread(r);
t.start();
|
|
Nov
2007 | Java Jazz Up |64 |
|
|
View All Topics |
All Pages of this Issue |
Pages:
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53 ,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63 ,
64,
65 ,
66 ,
67 ,
68 ,
69 Download PDF |
|
|
|
|
|
|
|
|
|