Usuário com melhor resposta
Socket Cliente - Apos desconectar nao conecta novamente

Pergunta
-
Preciso fazer uma conexão cliente servidor, no qual, o meio físico é instável e derruba a conexão algumas vezes, por isso minha aplicação cliente precisa conectar-se ao servidor enviar uma string e desconectar-se sempre que eu clicar em um botão (isso funciona perfeitamente na primeira vez que o botão é clicado) ao clicar pela segunda vez, uma Exceção ocorre dizendo que o socket está desconectado. Já tentei fazer socket simples e agora tentei o assíncrono, ambos ocorrem problemas semelhantes.
Segue abaixo minhas rotinas:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; namespace Teste_TCPIP_Assincrona { public partial class Form1 : Form { // State object for receiving data from remote device. // public class StateObject // { // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = 256; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public StringBuilder sb = new StringBuilder(); // } // public class AsynchronousClient // { // The port number for the remote device. private const int port = 8002; // ManualResetEvent instances signal completion. private static ManualResetEvent connectDone = new ManualResetEvent(false); private static ManualResetEvent disconnectDone = new ManualResetEvent(false); private static ManualResetEvent sendDone = new ManualResetEvent(false); private static ManualResetEvent receiveDone = new ManualResetEvent(false); // The response from the remote device. private static String response = String.Empty; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private static void StartClient() { try { //public IPAddress ipAddress = IPAddress.Parse("192.168.0.102");//ipHostInfo.AddressList[0]; IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("192.168.0.102"), port); // Create a TCP/IP socket. Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect to the remote endpoint. client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client); connectDone.WaitOne(); if (client.Connected) { // Send test data to the remote device. Send(client, "1" + "\n"); sendDone.WaitOne(); // Receive the response from the remote device. //Receive(client); //receiveDone.WaitOne(); // Write the response to the console. //Console.WriteLine("Response received : {0}", response); // Release the socket. client.Shutdown(SocketShutdown.Both); client.BeginDisconnect(true, new AsyncCallback(DisconnectCallback), client); // Wait for the disconnect to complete. disconnectDone.WaitOne(); client.Close(); if (client.Connected) MessageBox.Show("We're still connected"); else MessageBox.Show("We're disconnected"); } else MessageBox.Show("Não Reconectou"); } catch (Exception e) { MessageBox.Show(e.ToString()); } } private static void ConnectCallback(IAsyncResult ar) { try { // Retrieve the socket from the state object. Socket client = (Socket)ar.AsyncState; // Complete the connection. //client.EndConnect(ar); MessageBox.Show("Socket connected to: "+client.RemoteEndPoint.ToString()); // Signal that the connection has been made. connectDone.Set(); } catch (Exception e) { MessageBox.Show(e.ToString()); } } private static void Send(Socket client, String data) { // Convert the string data to byte data using ASCII encoding. byte[] byteData = Encoding.ASCII.GetBytes(data); // Begin sending the data to the remote device. client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); } private static void SendCallback(IAsyncResult ar) { try { // Retrieve the socket from the state object. Socket client = (Socket)ar.AsyncState; // Complete sending the data to the remote device. int bytesSent = client.EndSend(ar); MessageBox.Show("Sent " + bytesSent + " bytes to server."); // Signal that all bytes have been sent. sendDone.Set(); } catch (Exception e) { MessageBox.Show(e.ToString()); } } private static void DisconnectCallback(IAsyncResult ar) { // Complete the disconnect request. Socket client = (Socket)ar.AsyncState; client.EndDisconnect(ar); // Signal that the disconnect is complete. disconnectDone.Set(); } // } private void button1_Click(object sender, EventArgs e) { StartClient(); }
- Editado MMartins29 quinta-feira, 15 de outubro de 2015 22:35
Respostas
-
Boa noite,
Existem estes links abaixo que vão lhe ajudar no seu desenvolvimento.
Asynchronous Client Socket Example
https://msdn.microsoft.com/en-us/library/bew39x2a%28v=vs.110%29.aspxSynchronous Client Socket Example
https://msdn.microsoft.com/en-us/library/kb5kfec7%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396- Marcado como Resposta Marcos SJ sexta-feira, 16 de outubro de 2015 12:32
Todas as Respostas
-
Boa noite,
Existem estes links abaixo que vão lhe ajudar no seu desenvolvimento.
Asynchronous Client Socket Example
https://msdn.microsoft.com/en-us/library/bew39x2a%28v=vs.110%29.aspxSynchronous Client Socket Example
https://msdn.microsoft.com/en-us/library/kb5kfec7%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396- Marcado como Resposta Marcos SJ sexta-feira, 16 de outubro de 2015 12:32
-
Olá Cleber N Ramos,
Minha rotina foi totalmente baseada nesses exemplos, mas não está funcionando da maneira que necessito.
Obrigado.
- Editado Marcos SJ quinta-feira, 22 de outubro de 2015 18:57 Edição de nome de usuário