TcpClient hangs after connection to remote host & application freezes c# -
i trying establish connection remote host via ip address , port number. connection established (even verified using cmd netstat) when try close connection in code:
clientconnection.client.close(); clientconnection.client.dispose(); clientconnection.close();
the program crashes because socket not have available data read client stream. in windows application (client) have button click call connecttofalcon method , calls readstream method. please let me know have been going wrong.
public void readstream(object argument) { clientconnection = (tcpclient)argument; //tcpclient client = new tcpclient(); datetime start_time = datetime.now; timespan delay = new timespan(0, 0, 10); while (clientconnection.available == 0) { application.doevents(); if (datetime.now.subtract(start_time) > delay) break; } if ((clientconnection != null) && (clientconnection.available > 0)) { var message = new byte[1]; array.resize(ref message, clientconnection.available); //remove below 2 lines , if-statement block if program crashes clientconnection.client.receivetimeout = 20000; //timeout after 20 seconds clientconnection.sendtimeout = 20000; if (clientconnection.client.receivetimeout <= 20000 || clientconnection.sendtimeout == 20000) { clientconnection.client.receive(message); string testresult = system.text.encoding.default.getstring(message); } else { messagebox.show("time expired before read operation completed."); } } else if (((clientconnection == null) && (clientconnection.available <= 0)) || (clientconnection.connected == false)) { clientconnection.close(); messagebox.show("closing client connection due insufficient amount of data available read"); } //clientconnection.client.close(); //clientconnection.client.dispose(); //clientconnection.close(); }} public void connecttofalcon(string ipaddress, int port) { clientconnection = new tcpclient(); //var result = clientconnection.beginconnect(ipaddress, port, new asynccallback(callback), clientconnection); var result = clientconnection.beginconnect(ipaddress, port, null, null); var success = result.asyncwaithandle.waitone(timespan.fromseconds(1)); if (success == false) { messagebox.show("failed connect"); } else { messagebox.show("client connected..."); while (true) { thread t = new thread(readstream); t.start(clientconnection); //a new thread spawned //t.start(); } } }
according @luaan, must call endconnect on iasyncresult in callback function in order acknowledge client request.`
public void callback(iasyncresult ar) { this.clientconnection.endconnect(ar); } var result = clientconnection.beginconnect(ip, port, new asynccallback(callback), clientconnection);
Comments
Post a Comment