Biblioteca Java - Rev 3
Subversion Repositories:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lab.scd.net.chatsimple;
import java.net.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.*;
public class CServer extends Thread{
ArrayList clients = new ArrayList();
CServer(){
System.out.println("Starting!");
}
@Override
public void run() {
ServerSocket ss;
try {
ss = new ServerSocket(1999);
while(true){
Socket s = ss.accept();
System.out.println("Client nou conectat!");
clients.add(new TratareClient(s));
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendToAll(String msg){
for (Iterator iterator = clients.iterator(); iterator.hasNext();) {
TratareClient t = (TratareClient) iterator.next();
t.sendMessage(msg);
}
}
class TratareClient extends Thread{
BufferedReader in;
PrintWriter out;
TratareClient(Socket s) throws IOException{
out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()),true);
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
start();
}
public void sendMessage(String msg) {
out.println(msg);
}
@Override
public void run() {
try{
while(true){
String msg = in.readLine();
sendToAll(msg);
}
}
catch(Exception e){e.printStackTrace();}
}
}
public static void main(String[] args) {
CServer s = new CServer();
s.start();
}
}
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lab.scd.net.chatsimple;
import java.net.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.*;
public class CServer extends Thread{
ArrayList clients = new ArrayList();
CServer(){
System.out.println("Starting!");
}
@Override
public void run() {
ServerSocket ss;
try {
ss = new ServerSocket(1999);
while(true){
Socket s = ss.accept();
System.out.println("Client nou conectat!");
clients.add(new TratareClient(s));
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendToAll(String msg){
for (Iterator iterator = clients.iterator(); iterator.hasNext();) {
TratareClient t = (TratareClient) iterator.next();
t.sendMessage(msg);
}
}
class TratareClient extends Thread{
BufferedReader in;
PrintWriter out;
TratareClient(Socket s) throws IOException{
out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()),true);
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
start();
}
public void sendMessage(String msg) {
out.println(msg);
}
@Override
public void run() {
try{
while(true){
String msg = in.readLine();
sendToAll(msg);
}
}
catch(Exception e){e.printStackTrace();}
}
}
public static void main(String[] args) {
CServer s = new CServer();
s.start();
}
}