Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Mar 31st, 2008, 6:08 PM   #1
Kilo
Expert Programmer
 
Kilo's Avatar
 
Join Date: Nov 2005
Location: In Pink Clam?
Posts: 542
Rep Power: 0 Kilo is an unknown quantity at this point
Send a message via AIM to Kilo
Smile Returning data from a class

I'm working a a chat application for me and my girlfriend. Mu ultimate goal to is construct one class to utilize in both the client and server apps. The trouble I'm running into is being able to return recieved data back to the app from the class and post it in the text box. Below I will post the class constructor and a few linked methods it uses.

        public xsocket(int port, int maxCon, bool isServer)
        {
            i_Port = port;

            if (isServer)
            {
                i_maxConnections = maxCon;

                tcp_listener = new TcpListener(i_Port);
                tcp_listener.Start();
                s_serverIP = tcp_listener.LocalEndpoint.ToString();

                thd_tcp = new Thread(new ThreadStart(ListenLoop));
                hash_threads.Add(i_connectID, thd_tcp);
                thd_tcp.Start();
            }
            else
            {
                sock_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }
        }

        public void ListenLoop()
        {
            while (b_waitForClients)
            {
                sock_newClient = tcp_listener.AcceptSocket();

                if (hash_sockets.Count <= i_maxConnections)
                {
                    while (hash_sockets.Contains(i_connectID))
                    {
                        Interlocked.Increment(ref i_connectID);
                    }

                    thd_dataReader = new Thread(new ThreadStart(DataReader));

                    hash_sockets.Add(i_connectID, sock_newClient);
                    hash_threads.Add(i_connectID, thd_dataReader);

                    thd_dataReader.Start();
                }
            }
        }

        public void DataReader()
        {
            if (b_isServer)
            {
                i_userID = i_connectID;
                sock_dataRet = (Socket)hash_sockets[i_userID];

                while (true)
                {
                    if (sock_dataRet.Connected)
                    {
                        Byte[] b_newData = new Byte[1024];
                        try
                        {
                            int retrievedData = sock_dataRet.Receive(b_newData, b_newData.Length, 0);

                            if (retrievedData > 0)
                            {
                                string s_temp;
                                s_temp = Encoding.ASCII.GetString(b_newData);
                            }
                        }
                        catch
                        {
                            if (b_isServer)
                                RemoveClient(i_userID);
                        }
                    }
                }
            }
            else
            {
                Byte[] b_dataRet = new Byte[1024];
                string tempData;

                try
                {
                    int ret = sock_client.Receive(b_dataRet, b_dataRet.Length, 0);

                    if (ret > 0)
                    {
                        // find a way to return the data
                        tempData = Encoding.ASCII.GetString(b_dataRet);
                    }
                }
                catch
                {
                    // connection lost??? return error
                }
            }
        }

If you need anymore code let me know... I didn't want to spam it. Thanks!
__________________
"When in Rome, Do as the Romans Do"
"Beauty is in the eye of the BEER holder"
"Save your breath your going to need it for your blow up doll later"

SearchLores.org
Kilo is offline   Reply With Quote
Old Apr 1st, 2008, 7:12 AM   #2
kruptof
Professional Programmer
 
kruptof's Avatar
 
Join Date: May 2006
Location: UK - London
Posts: 329
Rep Power: 3 kruptof is on a distinguished road
Re: Returning data from a class

Why not just have an attribute and set that to the data returned.And have a getter method for that? Then in your main app you can just assign the texboes Text attribute to this value.

class Sock
{
private String data = "";;

public getData()
{
 return data;
}
...
}

and in your main app do:
Sock s = new Sock();
TextBox.Text = s.getData()
__________________
Quote:
When I was young it seemed that life was so wonderful,a miracle, oh it was beautiful, magical.
Now watch what you say or they'll be calling you a radical,a liberal, oh fanatical, criminal. Oh won't you sign up your name,we'd like to feel you're acceptable, respectable, oh presentable, a vegetable
kruptof is offline   Reply With Quote
Old Apr 1st, 2008, 11:54 AM   #3
Kilo
Expert Programmer
 
Kilo's Avatar
 
Join Date: Nov 2005
Location: In Pink Clam?
Posts: 542
Rep Power: 0 Kilo is an unknown quantity at this point
Send a message via AIM to Kilo
Re: Returning data from a class

Yea I thought that would have been a good quick fix too... but the main issue I'm running into is that this is a chat app and I'm not sure when the user will be sending data.... So i need to be able to detect from the application that the socket class has recieved new data. I believe this is a good time to implement some sort of event... but I have never made one..only utilized them.

thanks
__________________
"When in Rome, Do as the Romans Do"
"Beauty is in the eye of the BEER holder"
"Save your breath your going to need it for your blow up doll later"

SearchLores.org
Kilo is offline   Reply With Quote
Old Apr 2nd, 2008, 4:32 AM   #4
kruptof
Professional Programmer
 
kruptof's Avatar
 
Join Date: May 2006
Location: UK - London
Posts: 329
Rep Power: 3 kruptof is on a distinguished road
Re: Returning data from a class

Have an attribute in your class which is a delegate, (I think delegates work like function pointers, look it up) and when you receive data invoke the delegate. You need to set the delegate before the data receiver method is invoked, probably in the constructor.
__________________
Quote:
When I was young it seemed that life was so wonderful,a miracle, oh it was beautiful, magical.
Now watch what you say or they'll be calling you a radical,a liberal, oh fanatical, criminal. Oh won't you sign up your name,we'd like to feel you're acceptable, respectable, oh presentable, a vegetable
kruptof is offline   Reply With Quote
Old Apr 6th, 2008, 3:36 PM   #5
Kilo
Expert Programmer
 
Kilo's Avatar
 
Join Date: Nov 2005
Location: In Pink Clam?
Posts: 542
Rep Power: 0 Kilo is an unknown quantity at this point
Send a message via AIM to Kilo
Re: Returning data from a class

Thanks for your help so far man... much appreciated.

I ended up passing a ref to the textbox through the contructor. When data is recieved a function is called to update the ref to the textbox. I have now encountered a new problem. I can only send 1 msg from the client to the server. None from the client and no more than 1 from the server. I think The DataReader function is only being called the first time date arrives... what about the second time? Believe I'm posting the entire class. Is there something I need to do to link the DataReader function to an event handler for the socket.

EDIT: I noticed my code for the client sending is commented out. So i guess the only issue is the DataReader problem.

C# Syntax (Toggle Plain Text)
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Collections;
  7. using System.Threading;
  8. using System.Windows.Forms;
  9.  
  10. namespace Kraken
  11. {
  12. public class xsocket
  13. {
  14. public string s_serverIP = null;
  15.  
  16. //public delegate void del_DataHandler(string dataPost);
  17.  
  18. //public event del_DataHandler DataPost;
  19.  
  20. private Socket sock_newClient, sock_dataRet, sock_dataSend, sock_client;
  21.  
  22. private int i_connectID = 0, i_userID = 0, i_maxConnections = 100, i_Port;
  23.  
  24. private bool b_waitForClients = true, b_isServer;
  25.  
  26. private TcpListener tcp_listener;
  27. private Hashtable hash_sockets = new Hashtable();
  28. private Hashtable hash_threads = new Hashtable();
  29.  
  30. private Thread thd_tcp, thd_dataReader;
  31.  
  32. private TextBox tb_chatBox;
  33. //server,client
  34. public xsocket(int port, int maxCon, ref TextBox tb_tempChatBox, bool isServer)
  35. {
  36. i_Port = port;
  37. tb_chatBox = tb_tempChatBox;
  38. b_isServer = isServer;
  39.  
  40. if (b_isServer)
  41. {
  42. i_maxConnections = maxCon;
  43.  
  44. tcp_listener = new TcpListener(i_Port);
  45. tcp_listener.Start();
  46. s_serverIP = tcp_listener.LocalEndpoint.ToString();
  47.  
  48. thd_tcp = new Thread(new ThreadStart(ListenLoop));
  49. thd_tcp.Start();
  50. }
  51. else
  52. {
  53. sock_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  54. }
  55. }
  56. //server,client
  57. ~xsocket()
  58. {
  59. if(b_isServer)
  60. tcp_listener.Stop();
  61. if (thd_dataReader.IsAlive)
  62. thd_dataReader.Abort();
  63. if (thd_tcp.IsAlive)
  64. thd_tcp.Abort();
  65.  
  66. sock_newClient.Close();
  67. sock_dataRet.Close();
  68. sock_dataSend.Close();
  69. sock_client.Close();
  70. }
  71. //client,server
  72. protected void OnDataPost(string dataPost)
  73. {
  74. tb_chatBox.Text += dataPost + System.Environment.NewLine;
  75. }
  76. //client
  77. public string ClientConnect(string servIP, string nickName)
  78. {
  79. IPAddress ip_servAddy = IPAddress.Parse(servIP);
  80. IPEndPoint ep_ip = new IPEndPoint(ip_servAddy, i_Port);
  81.  
  82. try
  83. {
  84. sock_client.Connect(ep_ip);
  85.  
  86. if (sock_client.Connected)
  87. {
  88. // add nickname sending
  89. thd_dataReader = new Thread(new ThreadStart(DataReader));
  90. thd_dataReader.Start();
  91.  
  92. return "Connected to Kraken server.";
  93. }
  94. else
  95. return "Failed to connect.";
  96. }
  97. catch(Exception ex)
  98. {
  99. return ex.Message;
  100. }
  101. }
  102. //server
  103. public void ListenLoop()
  104. {
  105. while (b_waitForClients)
  106. {
  107. sock_newClient = tcp_listener.AcceptSocket();
  108.  
  109. if (hash_sockets.Count <= i_maxConnections)
  110. {
  111. while (hash_sockets.Contains(i_connectID))
  112. {
  113. Interlocked.Increment(ref i_connectID);
  114. }
  115.  
  116. thd_dataReader = new Thread(new ThreadStart(DataReader));
  117.  
  118. hash_sockets.Add(i_connectID, sock_newClient);
  119. hash_threads.Add(i_connectID, thd_dataReader);
  120.  
  121. thd_dataReader.Start();
  122. }
  123. }
  124. }
  125. //server,client
  126. public void DataReader()
  127. {
  128. if (b_isServer)
  129. {
  130. i_userID = i_connectID;
  131. sock_dataRet = (Socket)hash_sockets[i_userID];
  132.  
  133. while (true)
  134. {
  135. if (sock_dataRet.Connected)
  136. {
  137. Byte[] b_newData = new Byte[5000];
  138. try
  139. {
  140. int retrievedData = sock_dataRet.Receive(b_newData, b_newData.Length, 0);
  141.  
  142. if (retrievedData > 0)
  143. {
  144. OnDataPost(Encoding.ASCII.GetString(b_newData));
  145. }
  146. }
  147. catch
  148. {
  149. if (b_isServer)
  150. RemoveClient(i_userID);
  151. }
  152. }
  153. }
  154. }
  155. else
  156. {
  157. Byte[] b_dataRet = new Byte[5000];
  158.  
  159. try
  160. {
  161. int ret = sock_client.Receive(b_dataRet, b_dataRet.Length, 0);
  162.  
  163. if (ret > 0)
  164. {
  165. OnDataPost(Encoding.ASCII.GetString(b_dataRet));
  166. }
  167. }
  168. catch
  169. {
  170. // connection lost??? return error
  171. }
  172. }
  173. }
  174. //server
  175. public void StopAccepting()
  176. {
  177. b_waitForClients = false;
  178. }
  179. //server,client
  180. public void SendData(string tempSendData)
  181. {
  182. if (b_isServer)
  183. {
  184. foreach (int sock_keys in hash_sockets.Keys)
  185. {
  186. sock_dataSend = (Socket)hash_sockets[sock_keys];
  187.  
  188. if (sock_dataSend.Connected)
  189. {
  190. Byte[] b_sendData = Encoding.ASCII.GetBytes(tempSendData.ToCharArray());
  191.  
  192. try
  193. {
  194. sock_dataSend.Send(b_sendData, b_sendData.Length, 0);
  195. }
  196. catch
  197. {
  198. RemoveClient(sock_keys);
  199. }
  200. }
  201. }
  202. }
  203. else
  204. {
  205.  
  206.  
  207. //try
  208. //{
  209. // sock_dataSend.Send(b_sendData, b_sendData.Length, 0);
  210. //}
  211. //catch
  212. //{
  213. // RemoveClient(sock_keys);
  214. //}
  215. }
  216. }
  217. //server
  218. public void RemoveClient(int client)
  219. {
  220. Thread thd_removeClient = (Thread)hash_threads[client];
  221. hash_sockets.Remove(client);
  222. hash_threads.Remove(client);
  223. if (thd_removeClient.IsAlive)
  224. thd_removeClient.Abort();
  225. }
  226. //client
  227. public bool IsClientConnected()
  228. {
  229. return (sock_client.Connected);
  230. }
  231. }
  232. }
__________________
"When in Rome, Do as the Romans Do"
"Beauty is in the eye of the BEER holder"
"Save your breath your going to need it for your blow up doll later"

SearchLores.org
Kilo is offline   Reply With Quote
Old Apr 6th, 2008, 6:57 PM   #6
Jabo
Not a user?
 
Join Date: Sep 2007
Posts: 245
Rep Power: 1 Jabo is on a distinguished road
Re: Returning data from a class

This may help, I made a prog that pings various servers and emails results to me. I have to destroy each instance of ping and I think smtp message too before I can send another.
Jabo is offline   Reply With Quote
Old Apr 8th, 2008, 4:55 PM   #7
Kilo
Expert Programmer
 
Kilo's Avatar
 
Join Date: Nov 2005
Location: In Pink Clam?
Posts: 542
Rep Power: 0 Kilo is an unknown quantity at this point
Send a message via AIM to Kilo
Re: Returning data from a class

Hehe... I realized that it was looping the data reader... I accomplished that by throwing the code in a while loop and throwing it on it's own thread. The problem where a few simple corrections within the send and recieve functions.

Thanks for the help!
__________________
"When in Rome, Do as the Romans Do"
"Beauty is in the eye of the BEER holder"
"Save your breath your going to need it for your blow up doll later"

SearchLores.org
Kilo is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

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

Similar Threads
Thread Thread Starter Forum Replies Last Post
template class brad sue C++ 1 Mar 25th, 2007 5:46 PM
Class problem Ithaqua Visual Basic .NET 4 Dec 5th, 2006 4:30 PM
URL class Eric the Red Java 5 Jun 24th, 2006 9:01 PM
Problem with class constructor paeck C++ 8 Feb 7th, 2006 12:53 PM
Recommended Practice for returning data from function Arla C# 1 Aug 16th, 2005 12:21 PM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 9:59 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC