|
Hi all,
I'm very new to socket programming, this will probably come across in my question!
One of our partners provides a service to us over TCP/IP sockets. We can send them data over any number of sockets, while we're supposed to keep one socket open to receive data from them.
I have done the first part ok (us sending data to them), I can connect, login (a requirement of the service) and send them data, but I am struggling to set up the part where we receive. I want to create a Windows Service (although I'm testing with a console app) with a socket set to 'listen' (I think?!), which seems to be a bit more complicated.
The code is use to connect to send data looks like this (IP, port, username and password are all dummy values):
Socket mySocket, sServer = "1.1.1.1";
int iPort = 800;
IPHostEntry hostEntry = Dns.Resolve(sServer);
IPAddress[] ipAddresses = hostEntry.AddressList;
IPEndPoint hostEndPoint = new IPEndPoint(ipAddresses[0], iPort);
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Connect
mySocket.Connect(hostEndPoint);
if (mySocket.Connected)
{
Encoding ASCII = Encoding.ASCII;
string sLogin = "open tx username password\n";
byte[] bytLogin = ASCII.GetBytes(sLogin);
byte[] bytRec = new byte[256];
mySocket.Send(bytLogin, bytLogin.Length, 0);
int iRec = mySocket.Receive(bytRec, bytRec.Length, 0);
string sRec = ASCII.GetString(bytRec, 0, iRec);
if (sRec == "OK\n")
{
//Successfully logged in.
}
}
Is anyone able to point me in the right direction. I'm thinking that maybe I should be using the Listen() method of the Socket class, but I'm really not sure. If I try to call that after logging in as above I get the exception, "The requested address is not valid in its context".
Any help would be greatly appreciated! Thanks,
Toby
|
|
|
|
|
PS Apologies, the error I actually get is, "A connect request was made on an already connected socket".
|
|
|
|
|
Look into BeginReceive / BeginRead async methods of the socket class. These are event driven. Once you have logged in and established connectivity to their server, call beginrecieve. You can pass this a delegate to call as soon as data starts arriving, and in the meantime, you can send data down the same socket.
If you want more info, I can post some snippets tonight.... (now + about 8 hours).
Regards
Malc
*********************************************
|
|
|
|
|
Malc,
Great, thanks for that, I shall have a look at those methods and see if I can get any further. If it's no trouble to post that code later then please do - there's every chance I'll still be confused tonight, and even if not it would be good to see a working example.
Thanks again,
Toby
|
|
|
|
|
Hi,
If you want to receive data through sockets you can write a code like this one:
<code>
Socket tcpListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
m_tcpListener.Bind(new IPEndPoint(IPAddress.Any,<Port Number>));
m_tcpListener.Listen(<number of max connections>);
Socket client = m_tcpListener.AcceptSocket();
byte []buffer = new byte[1024];
int read = 0;
string message = "";
while ((read = client.Receive(buffer)) != 0)
{
message = String.Concat(message,Encoding.ASCII.GetString(buffer,0,read));
if (read < buffer.Length)
break;
}
</code>
This example read a message from a client socket. Inside the while structure you read the entire message (even if it's larger than 1KB).
Hope it helps.
Do your best to be the best
|
|
|
|
|
Hi,
And thanks for the suggestion, much appreciated. Do you know if I could incorporate my login bit into that? Something like the bit that starts:
string sLogin = "open tx username password\n";
in my original post? I need to do this to listen as well, but am not sure at which stage I would do so?
Cheers,
Toby
|
|
|
|
|
Hi,
The only thing that matters is that through sockets you have to send a byte array. It doesn't matter what that array contains. All that is important is that you must know what you are reading and in what order.
Do your best to be the best
|
|
|
|
|
Hi All
I am trying to make an application like MS Paint, and I don't know how to converting the drawings in my graphics object into an image and save it on the hard disk
is there anybody can help?
thx
|
|
|
|
|
Your graphics object can only be drawn to if it contains an Image or Bitmap, and the Bitmap class has a Save method to save it to disc.
Christian Graus - Microsoft MVP - C++
Metal Musings - Rex and my new metal blog
|
|
|
|
|
is this right way to bind data with texboxes when you use classes,i mean i need to display data on labels.
private void btnGo_Click(object sender, System.EventArgs e)
{
try
{
SearchCustomers search = new SearchCustomers();
string Barcode1;
string CustomerName="" ;
string Barcode;
string ProductName="";
string Price = "";
search.CustomerName = "jakes";
if(txtBarcode.Text.Length <4)
{
Barcode1 =txtBarcode.Text;
lblCustomerName.Text = CustomerName;
search.SeachCustomer( CustomerName, Barcode1);
}
else
{
Barcode = txtBarcode.Text;
lblProductName.Text = ProductName;
lblPrice.Text =Price;
search.SeachProduct(Barcode, ProductName, Price);
|
|
|
|
|
Hi, Every One
Kindly let me know that,, which is best? C# Expres Edition? OR C# Professional Edition?
|
|
|
|
|
Well, one is free. So, which do you think is better ?
Christian Graus - Microsoft MVP - C++
Metal Musings - Rex and my new metal blog
|
|
|
|
|
Hello
Depends on what you want to do with it
Regards
Oh! BTW: Sure the Pro is better;)
|
|
|
|
|
|
Hello,
This is what I'm trying to do.
Get the public folders out of each Exchange Server (that is visible through the Exchange System Manager). As the select * from exchange_PublicFolder only shows the folders at the highest level and not per storage group I looking at the ADSI approach.
this is the code so far. Parts have been commented out as I'm testing this new part with ADSI.
<br />
try<br />
{<br />
string cServername;<br />
ManagementObjectCollection mcExchange=queryServer(".","select * from Exchange_Server");<br />
txtNoOfServers.Text=mcExchange.Count.ToString();<br />
foreach(ManagementObject moExchange in mcExchange)<br />
{<br />
cServername = moExchange["Name"].ToString();<br />
<br />
<br />
<br />
string[] SQLArray=new string[7];<br />
<br />
SQLArray[0]="select * from Exchange_Mailbox where size <=10240";<br />
SQLArray[1]="select * from Exchange_Mailbox where size >" + 10240 + " and size <=" + 5*10240;<br />
SQLArray[2]="select * from Exchange_Mailbox where size >" + 5*10240 + " and size <=" + 10*10240;<br />
SQLArray[3]="select * from Exchange_Mailbox where size >" + 10*10240 + " and size <=" + 25*10240;<br />
SQLArray[4]="select * from Exchange_Mailbox where size >" + 25*10240 + " and size <=" + 50*10240;<br />
SQLArray[5]="select * from Exchange_Mailbox where size >" + 50*10240 + " and size <=" + 100*10240;<br />
SQLArray[6]="select * from Exchange_Mailbox where size >" + 100*10240;<br />
txtMB.Text=queryServer(cServername,"select * from Exchange_Mailbox").Count.ToString();<br />
int[] MBSizesArray= new int[7];<br />
lstMBSizes.Items.Add(cServername);<br />
for (int i=0;i<7;i++)<br />
{<br />
MBSizesArray[i]=queryServer(cServername,SQLArray[i]).Count;<br />
lstMBSizes.Items.Add(MBSizesArray[i].ToString());<br />
}<br />
DirectoryEntry rootdse=new DirectoryEntry("LDAP://RootDSE");<br />
DirectoryEntry cfg=new DirectoryEntry("LDAP://"+rootdse.Properties["configurationnamingcontext"].Value);<br />
DirectorySearcher cfgsearch=new DirectorySearcher(cfg);<br />
cfgsearch.Filter="(&(objectCategory=msExchExchangeServer)cn="+cServername +")";<br />
cfgsearch.PropertiesToLoad.Add("distinguishedName");<br />
cfgsearch.SearchScope=SearchScope.Subtree;<br />
SearchResult res=cfgsearch.FindOne();<br />
SearchResultCollection resStorageGroups=searchContainer(res.Properties["distinguishedName"][0].ToString(),"&(objectCategory=msExchStorageGroup)");<br />
<br />
foreach (SearchResult sg in resStorageGroups)<br />
{<br />
SearchResultCollection resMailboxes=searchContainer(sg.Properties["distinguishedName"][0].ToString(),"&(objectCategory=msExchPrivateMDB)");<br />
foreach(SearchResult mb in resMailboxes)<br />
{<br />
<br />
<br />
}<br />
<br />
}<br />
<br />
<br />
<br />
DateTime startTime=new DateTime(System.DateTime.Now.Year,System.DateTime.Now.Month,System.DateTime.Now.Day-1);<br />
DateTime endTime=startTime.AddHours(24);<br />
<br />
string sTime=startTime.ToString("yyyyMMdd")+ "000000.000000+000";<br />
string eTime=endTime.ToString("yyyyMMdd")+ "000000.000000+000";<br />
<br />
<br />
ManagementObjectCollection mc=queryServer(cServername,"select * from Exchange_MessageTrackingEntry where Timelogged>='" + sTime + "' and TimeLogged<'" + eTime+"'");<br />
txtMailVolumeMsg.Text=mc.Count.ToString();<br />
Double ttlSize=0;<br />
foreach(ManagementObject mo in mc)<br />
{<br />
ttlSize+=Convert.ToDouble(mo["Size"])/(1024*1024); <br />
}<br />
txtMailVolumeMB.Text=ttlSize.ToString();<br />
<br />
<br />
<br />
<br />
<br />
<br />
}<br />
}<br />
catch (Exception ex)<br />
{<br />
MessageBox.Show(ex.ToString());<br />
}<br />
<br />
<br />
<br />
}<br />
<br />
private ManagementObjectCollection queryServer(string servername,string querystring)<br />
{<br />
try<br />
{<br />
System.Management.ConnectionOptions objconn = new System.Management.ConnectionOptions();<br />
objconn.Impersonation = System.Management.ImpersonationLevel.Impersonate;<br />
objconn.EnablePrivileges = true;<br />
System.Management.ManagementScope exmangescope = new System.Management.ManagementScope(@"\\" + servername + @"\root\MicrosoftExchangeV2",objconn);<br />
System.Management.ObjectQuery objquery = new System.Management.ObjectQuery(querystring);<br />
System.Management.ManagementObjectSearcher objsearch = new System.Management.ManagementObjectSearcher(exmangescope,objquery);<br />
return objsearch.Get();<br />
}<br />
catch (Exception e)<br />
{<br />
MessageBox.Show(e.ToString());<br />
return null;<br />
}<br />
}<br />
<br />
private SearchResultCollection searchContainer(string p,string fltr)<br />
{<br />
try<br />
{<br />
DirectoryEntry serverContainer=new DirectoryEntry("LDAP://"+p);<br />
DirectorySearcher serverSearch=new DirectorySearcher(serverContainer);<br />
serverSearch.Filter=fltr;<br />
serverSearch.SearchScope=SearchScope.Subtree;<br />
serverSearch.PropertiesToLoad.Add("cn");<br />
serverSearch.PropertiesToLoad.Add("distinguishedName");<br />
serverSearch.PropertiesToLoad.Add("homeMDBBL");<br />
SearchResultCollection result=serverSearch.FindAll();<br />
<br />
return result;<br />
}<br />
catch (Exception srcex)<br />
{<br />
MessageBox.Show(srcex.ToString());<br />
<br />
}<br />
}
msExchPrivateMDB is the name to select the mailbox data. I'm sure there must be one for public folders as well ?
Any help would be greatly appreciated.
|
|
|
|
|
when I am pressing backspace I want some variable value should change(i=3).So how to do it
|
|
|
|
|
Hi,
You can write the code in KeyPress event. You get e.KeyChar. Check if it is Backspace and if yes execute some code. as simple as that !
"A good programmer is someone who looks both ways before crossing a one-way street." -- Doug Linder
Anant Y. Kulkarni
|
|
|
|
|
Hi,
In my application i need to know when the monitor has changed state from stby to normal.
I know how to put it to stby using SendMessage, but what i need to know is when it wakes up (when the user uses the mouse or keyboard, for eg..).
Any help is appreciated.
Roy
|
|
|
|
|
I have unmanged DLL (legacy - can't touch it!) which returns an XML string. I want to bind this string to a datagrid....easy...or it should be. But I can't. I've isolated the problem below. To get the xml string into a dataset, I use a StringReader and use ReadXml . But when binding to Datagrid, it only shows the root node if I haven't pre bound the columns, or if I have, it complains the field isn't there (as it only exists in teh child nodes). I have saved the output from the Unmanaged DLL to an XML file which can be parsed, so the format is correct.
To test, I use two methods of populating the grid. The first one works fine, loading the XML file into an XMLDataSource . The second one doesn't - loading the XML file into a DataSource , via ReadXML . It is this second optoin I need to work, or some method of doing this where i can pass an XML string in.
works a treat, but I can't use as I have to receive from a string, not a file
XmlDataSource xds = new XmlDataSource();
xds.DataFile = ("d:/test.xml");
GridView1.DataSource = xds;
GridView1.DataBind();
doesn't work as it only seems to look at root node.
DataSet ds = new DataSet();
System.IO.StreamReader str = new StreamReader("d:/test.xml") ;
StringReader rdr = new StringReader(str.ReadToEnd());
ds.ReadXml(rdr);
GridView1.DataSource = ds;
GridView1.DataBind();
Any ideas?
Regards
Malc
*********************************************
|
|
|
|
|
err
maybe you should use ReadXmlSchema().
|
|
|
|
|
The Dataset, read from an XML string contains multiple tables. The first table (the default) is the root node, the second table, contains the child nodes...so...changing the following line works a treat..
GridView1.DataSource = ds.Tables[1];
Regards
Malc
*********************************************
|
|
|
|
|
Hi Guys,
I'm tryin to Post an xml string to a web service which returns an xml string use WebRequest.
I'm getting the following error.
Error in Order System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream()
Any hints tips or preferable solutions!!!!
Thanks in advance
Will
Will
I'm a man who discovered the wheel and built the Eiffel Tower out of metal and brawn. That's what kind of man I am. You're just a woman with a small brain. With a brain a third the size of us. It's science. - Ron Burgundy - Anchorman
|
|
|
|
|
Can anyone tell me howa user can connect to the internt using my software. I want the user to be able to feed in the username and password and when Connect is clicked - the application connects using a network conmection on the computer. I would also be able to check wether authentication was successful and the connection state. Whioh library do i have to use. I tried googling it up but i couldnt find anything specific. I believe it is called "RAS" - am i correct? Thanks all.
|
|
|
|
|
Hello
Why use a 3rd library. You got all you need in System.Net namespace and namespaces derived from it like System.Net.NetworkInformation
Regards
|
|
|
|
|
Dear gurus,
I have a generics question.
// T is either Int32 or Double
void fkt<T>( ref T someValue ) where T : IConvertible
{
Int32 i = 5;
someValue = i; <---- compiler error here
someValue = (T)i; <---- compiler error here
}
In both cases I get a type conversion error
How can I handle this? I know in advance, that T is only Int32 or Double.
Thanks for your help
-- modified at 4:58 Thursday 17th August, 2006
|
|
|
|
|