You are on page 1of 8

import java.awt.

Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

import java.io.*;
import java.net.*;

class ClientWorker implements Runnable {


public Socket client;
private JTextArea textArea;
public SocketThrdServer Root;
public String Data="null";
ClientWorker(Socket client, JTextArea textArea,SocketThrdServer root) {
this.client = client;
this.textArea = textArea;
this.Root = root;

}
public void SendData(String str,Socket cl)
{
System.out.println("Started Sending Data");
BufferedReader lin = null;
PrintWriter lout = null;
try{
if(cl.isConnected()==true)
{
lin = new BufferedReader(new
InputStreamReader(cl.getInputStream()));
lout = new PrintWriter(cl.getOutputStream(), true);
//lin.mark(0);
//lin.reset();

}
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}

if(cl.isConnected()==true)
{
lout.println(str);lout.flush();
System.out.println("Sending Data successful");

}
else{System.out.println("Sending Data failed");}
}

public void run(){


System.out.println("started to run");
String line;
InputStreamReader ins;
BufferedReader insBuffer;
char cbuf[] = new char[100];//{' ',' ',' ',' ',' ',' '};
cbuf=EmptyChars(cbuf);
BufferedReader in = null;
PrintWriter out = null;
String PolicyString ="<?xml version="+"1"+"."+"0?>"
+"<cross-domain-policy>"
+"<allow-access-from domain="+"*"+"to-ports=4444 />"
+"</cross-domain-policy>";

PolicyString =
"<?xml version='1.0'?>"
+"<cross-domain-policy>"
+"<allow-http-request-headers-from domain='*' headers='*' secure='false' />"
+"<allow-access-from domain='*' "+"to-ports=4444 secure='false' />"
+"</cross-domain-policy>";
line="null";
String POLICY_XML =
"<?xml version='1.0'?>"
+ "<cross-domain-policy>"
+ "<allow-access-from domain=* to-ports=* />"
+ "</cross-domain-policy>";
try{
System.out.println("trying to get buffer readers");
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);

//if(in.readLine() =="<policy-file-request/>")
//{
// System.out.println("POLICY SENT");
// out.println(PolicyString);
//}
//in.mark(0);
//in.reset();
//out.println(PolicyString);
//out.flush();
//System.out.println("p SENT");
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}

while(client.isConnected())
{
try{
//System.out.println("trying to get buffer readers");
in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}
try{
//System.out.println("trying to get insBuffer");
//ins = new InputStreamReader(client.getInputStream());
//insBuffer = new BufferedReader(ins);
if (in.ready()==false){continue;}
System.out.println("reading cbuf from:"+in.toString());
//ins.read(cbuf);
in.read(cbuf);
in.mark(0);
in.reset();
System.out.println("Got cbuf");
line = ConvertToString(cbuf);
line=line.trim();
cbuf=EmptyChars(cbuf);
System.out.println("Got All Buffers:------:");
//out.print("data:"+line);
//out.flush();
this.Data = line;
Root.BroadCastData = line;
Root.BrodCast("Welcome",Root.ClientCount,Root.AllClientWorkers);
}
catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
try {
in.close();
out.close();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
//while(1==1){
// try{
// ins = new InputStreamReader(client.getInputStream());
// insBuffer = new BufferedReader(ins);
// ins.read(cbuf);
// line = ConvertToString(cbuf);
// line=line.trim();
// cbuf=EmptyChars(cbuf);

//line = in.readLine();
//Send data back to client
//||<>
//out.println("asdfsdf");
//out.flush();
//Root.BrodCast("str", Root.ClientCount, Root.AllClientWorkers);
//Root.BrodCast("Welcome",Root.ClientCount,Root.AllClientWorkers);

// textArea.append("cycle");
// } catch (IOException e) {
// System.out.println("Read failed");
// System.exit(-1);
// }
//}

}
public static char[] EmptyChars(char[] str)
{
int i;
for (i=0;i < str.length;i++)
{
str[i]=' ';
}
return str;
}
public void BC() throws IOException
{
MulticastSocket socket = new MulticastSocket(4444);
InetAddress group = InetAddress.getByName("230.0.0.1");
socket.joinGroup(group);

DatagramPacket packet;
for (int i = 0; i < 5; i++) {
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);

String received = new String(packet.getData());


System.out.println("Quote of the Moment: " + received);
}
socket.leaveGroup(group);
socket.close();

}
public static String ConvertToString(char chars[])
{
int i;
StringBuffer strBuf;
strBuf= new StringBuffer();
for (i=0;i < chars.length;i++)
{
strBuf.append((char)chars[i]);
}

return (strBuf.toString());
}
}
//||<>
class SocketThrdServer extends JFrame{

JLabel label = new JLabel("Text received over socket:");


JPanel panel;
JTextArea textArea = new JTextArea();
ServerSocket server = null;
public ClientWorker[] AllClientWorkers= new ClientWorker[50];
int ClientCount=0;
String BroadCastData = "null";
public SocketThrdServer() throws IOException{ //Begin Constructor
panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBackground(Color.white);
getContentPane().add(panel);
panel.add("North", label);
panel.add("Center", textArea);

DatagramSocket socket = new DatagramSocket(4444);


byte[] buf = new byte[256];
InetAddress group = InetAddress.getByName(
"230.0.0.1");
DatagramPacket packet;
packet = new DatagramPacket(buf, buf.length,
group, 4446);
socket.send(packet);

} //End Constructor
public SocketThrdServer Root;

public void SetRoot(SocketThrdServer theRoot)


{
this.Root = theRoot;
}

public void BrodCast(String Data,int Count,ClientWorker[] Clients)


{

System.out.println("BrodCasting to "+Count+" Clients");


int i = 0;

for (i=1;i < Count+1;i++)


{
Clients[0].SendData(this.BroadCastData, Clients[i-1].client);
}
System.out.println("BrodCasting to "+Count+" Clients Finished");
}
public void listenSocket(){
try{
server = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
}
while(true){
ClientWorker w;

try{
w = new ClientWorker(server.accept(), textArea,Root);
textArea.append(w.client.getInetAddress().getHostAddress()+" connected to
port:"+w.client.getPort());

if(CheckArrayMatch(AllClientWorkers,w.client.getPort(),ClientCount)==false
)
{
AllClientWorkers[ClientCount]=w;
System.out.println("added a new client to the array at
pos:"+ClientCount+"with port:"+w.client.getPort());
ClientCount++;
}
//AllClientWorkers[ClientCount]=w;ClientCount++;
System.out.println("Nr of All client workers in array:"+ClientCount);
Thread t = new Thread(w);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
//BrodCast("Welcome",ClientCount,AllClientWorkers);

//System.out.println("name:"+w.toString());
if(1==0){break;}
}System.out.println("exited");
}
public static boolean CheckArrayMatch(ClientWorker[] arrayToCheck,int match,int
Len)
{
int i;
for(i=0;i < Len;i++)
{
//System.out.println(arrayToCheck[i].+":vs:"+match);
if( (arrayToCheck[i].client.getLocalPort() == match))
{
return true;
}
}
System.out.println(":no match");
return false;
}
protected void finalize(){
//Objects created in run method are finalized when
//program terminates and thread exits
try{
server.close();
} catch (IOException e) {
System.out.println("Could not close socket");
System.exit(-1);
}
}

public static void main(String[] args) throws IOException{


SocketThrdServer frame = new SocketThrdServer();
frame.SetRoot(frame);
frame.setTitle("Server Program");
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};

frame.addWindowListener(l);
frame.pack();
frame.setVisible(true);
frame.listenSocket();
}
}

//----------POLICY SERVER FROM HERE ON------------------


class PolicyServerConnection extends Thread {
protected Socket socket;
protected BufferedReader socketIn;
protected PrintWriter socketOut;

/**
* Creates a new instance of PolicyServerConnection.
*
* @param socket client's socket connection
*/
public PolicyServerConnection(Socket socket) {
this.socket = socket;
}

/**
* Create a reader and writer for the socket and call readPolicyRequest.
*/
public void run() {
try {
this.socketIn = new BufferedReader(new
InputStreamReader(this.socket.getInputStream()));
this.socketOut = new PrintWriter(this.socket.getOutputStream(), true);
readPolicyRequest();
}
catch (Exception e) {
System.out.println("Exception (run): " + e.getMessage());
}
}

/**
* Reads a string from the client and if it is a policy request we write the
policy, then we close the connection.
*/
protected void readPolicyRequest() {
try {
String request = socketIn.readLine();
System.out.println("client says '" + request + "'");

if (request.equals(PolicyServer.POLICY_REQUEST)) {
writePolicy();
}
}
catch (Exception e) {
System.out.println("Exception (readPolicyRequest): " + e.getMessage());
}
//finalize();
}

/**
* Writes the policy of the server.
*/
protected void writePolicy() {
try {
this.socketOut.write(PolicyServer.POLICY_XML + "u0000");
this.socketOut.close();
System.out.println("policy sent to client");
}
catch (Exception e) {
System.out.println("Exception (writePolicy): " + e.getMessage());
}
}
}

class PolicyServer extends Thread {


public static final String POLICY_REQUEST = "<policy-file-request/>";
public static final String POLICY_XML =
"<?xml version='1.0'?>"
+ "<cross-domain-policy>"
+ "<allow-access-from domain=* to-ports=* />"
+ "</cross-domain-policy>";

protected int port;


protected ServerSocket serverSocket;
protected boolean listening;

/**
* Creates a new instance of PolicyServer.
*
* @param serverPort the port to be used by the server
*/
public PolicyServer(int serverPort) {
this.port = serverPort;
this.listening = false;
}

/**
* Waits for clients' connections and handles them to a new
PolicyServerConnection.
*/
public void run() {
try {
this.serverSocket = new ServerSocket(this.port);
this.listening = true;
System.out.println("listening");

while (this.listening) {
Socket socket = this.serverSocket.accept();
System.out.println("client connection from " +
socket.getRemoteSocketAddress());
PolicyServerConnection socketConnection = new
PolicyServerConnection(socket);
socketConnection.start();
};
}
catch (Exception e) {
System.out.println("Exception (run): " + e.getMessage());
}
}
}

You might also like