Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 11-12-2004, 02:56 PM   PM User | #1
ghell
Senior Coder

 
Join Date: Apr 2003
Location: England
Posts: 1,192
Thanks: 5
Thanked 13 Times in 13 Posts
ghell is on a distinguished road
java tcp client communication

i can get a tcp server to communicate with a client, and thread this to simultaneously communicate with more clients, but i dont know how to get the clients to be able to hear each other, i cant seem to even loop through clients to send to when i want the server to reply

does anyone know how to do this, or have a simple tutorial on it?

i cant really post a section of code as im currently trying this in like 9 different files

edit: ps, threads really confuse me
__________________
My tech/code blog
ghell is offline   Reply With Quote
Old 11-14-2004, 11:51 PM   PM User | #2
Antoniohawk
Senior Coder

 
Join Date: Aug 2002
Location: Kansas City, Kansas
Posts: 1,518
Thanks: 0
Thanked 2 Times in 2 Posts
Antoniohawk will become famous soon enough
This is probably not what you want to hear, but without some sort of code, it's gonna be really difficult for anyone to even start to help ya out. Maybe you could at least post a portion of what you have.
Antoniohawk is offline   Reply With Quote
Old 11-16-2004, 12:32 PM   PM User | #3
ghell
Senior Coder

 
Join Date: Apr 2003
Location: England
Posts: 1,192
Thanks: 5
Thanked 13 Times in 13 Posts
ghell is on a distinguished road
hehe, you are right, that isnt what i wanted to hear

you dont really need code though (i have no bugs i just dont know how to do it), i have a client talkin to a server, and another client talkin to a server, but i cant get the server to reply echo everything it accepts to every threaded socket it has made

as i cant get to my code from college ill just post some links (i didnt use these but you might get an idea of what im trying to do with them)
confusing: http://www.nakov.com/inetjava/lectur...P-Sockets.html
more like it: http://discolab.rutgers.edu/users/mu...r01/notes.rec1 (from "Concurrent programming in java: Using threads
" onwards)
i think i used this one at some point: http://jan.netcomp.monash.edu.au/dis...t/lecture.html
might be useful but i cant access from here: http://csis.pace.edu/~bergin/InternetProgramming.html


etc... im just googling for "java tcp multithread socket" or something similar
__________________
My tech/code blog
ghell is offline   Reply With Quote
Old 11-18-2004, 03:39 PM   PM User | #4
ghell
Senior Coder

 
Join Date: Apr 2003
Location: England
Posts: 1,192
Thanks: 5
Thanked 13 Times in 13 Posts
ghell is on a distinguished road
i have now posted on forums.java.sun.com at http://forum.java.sun.com/thread.jsp...rt=0&trange=15 but i really hate that forum as no1 gives any answers whatsoever, they generally just tell me how dumb i am and to start smaller.. but i did start small. i just got this far and got stuck

anyway, any answers would be nice
__________________
My tech/code blog
ghell is offline   Reply With Quote
Old 11-19-2004, 02:24 PM   PM User | #5
rynox
New Coder

 
Join Date: Aug 2002
Posts: 73
Thanks: 0
Thanked 0 Times in 0 Posts
rynox is an unknown quantity at this point
I happen to be working on a multi-threaded server project as well. I have my main class (with entry point) and an rServer class that extends Thread. Each time a socket connection is made to the server socket a new rServer thread is fired up to handle it. One thing I wanted to do is be able to enumerate all of the client threads (class rServer) from my main class so I could yield() or whatever I wanted to do to those. I don't see why, in your situation, you couldn't store outputstreams or even the rServer objects themselves:

1. I created a new class called rServerRegistrar. It has 3 public methods void registerThread(Thread), void deregisterThread(Thread), and Thread[] getClientThreads().

2. In my main class I create an instance of rServerRegistrar and PASS THE INSTANCE TO EACH rServer OBJECT. Note that I can not just create a new instance of the registrar object in rServer (Maybe if I made it a static class I could. Is there such a thing as a static class???).

3. In the run() method of my rServer object, the first action is to register the thread rServerRegistrar.registerThread(this);

Now, in my main class, or rServer class, at any point I can use the method rServerRegistrar.getClientThreads() to get an array of Threads.

One problem I ran into was that if clients disconnected without issuing the correct command on the server, it would not properly deregister, so there would be threads returned that were not active, so in my getClientThreads() method I had to do some clean-up. I tried Thread.isActive(), but this doesn't seem to work. Still working on this problem.

rynox
rynox is offline   Reply With Quote
Old 11-19-2004, 02:26 PM   PM User | #6
rynox
New Coder

 
Join Date: Aug 2002
Posts: 73
Thanks: 0
Thanked 0 Times in 0 Posts
rynox is an unknown quantity at this point
Code:
public class rServerRegistrar {

	public Thread[] cthreads;

	public rServerRegistrar(Thread thr) {
		cthreads=new Thread[1];
		cthreads[0]=thr;
	}
	
	public void registerThread(Thread newthread) {
		Thread[] tempthreads=new Thread[cthreads.length+1];
		for(int i=0;i<cthreads.length;i++) {
			tempthreads[i]=cthreads[i];
		}
		tempthreads[cthreads.length]=newthread;
		cthreads=tempthreads;
	}
	
	public void deregisterThread(Thread delthread) {
		Thread[] tempthreads=new Thread[cthreads.length-1];
		int count=0;
		for(int i=0;i<cthreads.length;i++) {
			if(delthread.getName()!=cthreads[i].getName()) {
				tempthreads[count]=cthreads[i];
				count++;
			}
		}
		cthreads=tempthreads;
	}
	
	private void updateThreads() {
		int count=0; // First count the number of alive threads.
		for(int i=0;i<cthreads.length;i++) {
			if(cthreads[i].isAlive()) count++;
		}
		Thread[] temp=new Thread[count];
		count=0;
		for(int i=0;i<cthreads.length;i++) {
			if(cthreads[i].isAlive()) {
				temp[count]=cthreads[i];
				count++;
			}
		}
	}
	
	public Thread[] getClientThreads() {
		updateThreads(); // Return all except first thread.
		Thread[] temp=new Thread[cthreads.length-1];
		for(int i=0;i<temp.length;i++) {
			temp[i]=cthreads[i+1];
		}
		return temp;
	}

}
rynox is offline   Reply With Quote
Old 11-19-2004, 03:05 PM   PM User | #7
ghell
Senior Coder

 
Join Date: Apr 2003
Location: England
Posts: 1,192
Thanks: 5
Thanked 13 Times in 13 Posts
ghell is on a distinguished road
i wasnt sure if you were posting a question or an answer but ill play around with that to see if i can get it workin

Quote:
One problem I ran into was that if clients disconnected without issuing the correct command on the server, it would not properly deregister, so there would be threads returned that were not active, so in my getClientThreads() method I had to do some clean-up. I tried Thread.isActive(), but this doesn't seem to work. Still working on this problem.
if the client is in an applet cant you just make it do something when it is closed (destroy() or something... like.. you know... init() start()......destroy() or something.. im not sure if this works if the client machine does something like explode or have a powercut or get abducted by aliens or something of that nature )
__________________
My tech/code blog
ghell is offline   Reply With Quote
Old 11-21-2004, 02:08 PM   PM User | #8
ghell
Senior Coder

 
Join Date: Apr 2003
Location: England
Posts: 1,192
Thanks: 5
Thanked 13 Times in 13 Posts
ghell is on a distinguished road
i seem to have messed it up even more (port# censored but its there really )

server:
Code:
import java.lang.*;
import java.io.*;
import java.net.*;

public class Server
{
	public static void main(String args[])
	{
		String data;
		int intPort = ####;
		
		ServerSocket		objServerSocket;
		Socket			objSocket;
		InputStreamReader	objInStreamReader;
		BufferedReader		objInBuffer;
		PrintWriter		objOutStream;
		
		try
		{
			//---Start listening on port---
			objServerSocket = new ServerSocket(intPort);
			
			objSocket = objServerSocket.accept();
			System.out.println("Client has connected to server!");
			
			//---Set up streams---
			objInStreamReader = new InputStreamReader(objSocket.getInputStream());
			objInBuffer = new BufferedReader(objInStreamReader);
			
			objOutStream = new PrintWriter(objSocket.getOutputStream(), true);
			
			//---Receive Data---
			while (objInBuffer.ready())
			{
				data = objInBuffer.readLine();
				
				//---Echo clients data back---
				System.out.println("Echoing string: '" + data + "'");
				objOutStream.print(data);
			}
			
			//---Clean Up---
			objOutStream.close();
			objSocket.close();
			objServerSocket.close();
		}
		catch(BindException be)
		{
			System.out.println("BindException: \n\t" + "Port " + intPort + " already in use");
		}
		catch(Exception e)
		{
			System.out.println("Exception: \n\t" + e);
		}
	}
}
outputs:
Quote:
---BUILDING---
---RUNNING---
Client has connected to server!
Press any key to continue . . .
client:
Code:
import java.lang.*;
import java.io.*;
import java.net.*;

public class Client
{
	public static void main(String args[])
	{
		String data = "DataFromClient";
		
		Socket			objSocket;
		InputStreamReader	objInStreamReader;
		BufferedReader		objInBuffer;
		PrintWriter		objOutStream;
		
		//---Get Address---
		String strFullAddress = args[0];	//"localhost:####";
		
		String[] arrFullAddress = strFullAddress.split(":");
		String strAddress = arrFullAddress[0];
		int intPort = Integer.parseInt( arrFullAddress[1] );
		
		//System.out.println("Address:\t" + strAddress + "\nPort:\t\t" + intPort);
		//-----------------
		
		//String strAddress = "localhost";
		//int intPort = ####;
		
		try
		{
			System.out.println("Connecting to: '" + strFullAddress + "'");
			objSocket = new Socket(strAddress, intPort);
			
			objInStreamReader = new InputStreamReader(objSocket.getInputStream());
			objInBuffer = new BufferedReader(objInStreamReader);
			
			objOutStream = new PrintWriter(objSocket.getOutputStream(), true);
			
			//---Send Line---
			System.out.println("Sending string: '" + data + "'");
			objOutStream.print(data);
			
			while (objInBuffer.ready())
			{
				//---Receive and Print Line---
				System.out.println("Receiving String: '" + objInBuffer.readLine() + "'");
			}
			
			//---Clean Up---
			objOutStream.close();
			objInBuffer.close();
			objSocket.close();
		}
		catch(ConnectException ce)
		{
			System.out.println("Could not connect to server");
		}
		catch(Exception e)
		{
			System.out.println("Exception: \n\t" + e);
		}
	}
}
outputs:
Quote:
---BUILDING---
---RUNNING---
Connecting to: 'localhost:####'
Sending string: 'DataFromClient'
Press any key to continue . . .
when i had server sending data and client receiving it worked, but when i set client to send and then server to receive and echo back, it stopped, i dont know which side its stopped on
__________________
My tech/code blog
ghell is offline   Reply With Quote
Old 11-22-2004, 07:18 PM   PM User | #9
rynox
New Coder

 
Join Date: Aug 2002
Posts: 73
Thanks: 0
Thanked 0 Times in 0 Posts
rynox is an unknown quantity at this point
I don't know, bro. Check out my attachment. I created a server that will do just what you are looking for. A client can connect and it will echo what the other clients are typing.

I even tried to open it up as a url in a browser and I could see the entire browser request, nifty.
Attached Files
File Type: zip rserver.zip (2.9 KB, 447 views)
rynox is offline   Reply With Quote
Old 11-22-2004, 07:19 PM   PM User | #10
rynox
New Coder

 
Join Date: Aug 2002
Posts: 73
Thanks: 0
Thanked 0 Times in 0 Posts
rynox is an unknown quantity at this point
By the way, Library contains the void main() entry point.
rynox is offline   Reply With Quote
Old 11-23-2004, 08:43 AM   PM User | #11
ghell
Senior Coder

 
Join Date: Apr 2003
Location: England
Posts: 1,192
Thanks: 5
Thanked 13 Times in 13 Posts
ghell is on a distinguished road
thanks, ill try that when i get home tonight

the other one is getting a bit complicated but ill keep going with that one too
__________________
My tech/code blog
ghell is offline   Reply With Quote
Old 11-24-2004, 12:08 PM   PM User | #12
ghell
Senior Coder

 
Join Date: Apr 2003
Location: England
Posts: 1,192
Thanks: 5
Thanked 13 Times in 13 Posts
ghell is on a distinguished road
it didnt seem to echo anything at all (when i conencted it sent something like
"rServer 4.11
Connected."

but nothing i sent to it was echod back
__________________
My tech/code blog
ghell is offline   Reply With Quote
Old 11-26-2004, 01:15 PM   PM User | #13
rynox
New Coder

 
Join Date: Aug 2002
Posts: 73
Thanks: 0
Thanked 0 Times in 0 Posts
rynox is an unknown quantity at this point
It won't echo back to the client that sent the message. Make two connections to the server and you'll see what I mean.
rynox is offline   Reply With Quote
Old 11-26-2004, 03:29 PM   PM User | #14
rynox
New Coder

 
Join Date: Aug 2002
Posts: 73
Thanks: 0
Thanked 0 Times in 0 Posts
rynox is an unknown quantity at this point
Here's why:

Line 1, I made this synchronized because many different threads could access this method at once if I didn't. I encountered race problems.
Line 2, Return an array of rServer (client) threads.
Line 3, for loop to loop through active client threads
Line 5, if thread is not current client thread...
Line 6, echo to client's Outputstream.

Code:
 1	public synchronized void command(String cmd, rServer t) {
 2		rServer[] rsv=rsr.getClientThreads();
 3		for(int i=0;i<rsv.length;i++) {
 4			try {
 5				if(rsv[i]!=t) {
 6					rsv[i].out.writ...
 7				}
 8			} catch (Exception e) { }
 9		}
10	}
rynox is offline   Reply With Quote
Old 11-26-2004, 05:16 PM   PM User | #15
ghell
Senior Coder

 
Join Date: Apr 2003
Location: England
Posts: 1,192
Thanks: 5
Thanked 13 Times in 13 Posts
ghell is on a distinguished road
oooohh nice 1 m8

ill prob have to just take the theory from this and put it into my own to get it to do exactly what i want it to do, and ofc its just cheating if i steal it

just out of curiosity, did you just make this ages ago for use in all client server communication stuffs you make or what... seems like a lot of effort to help me
__________________
My tech/code blog
ghell is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 06:44 PM.


Advertisement
Log in to turn off these ads.