我把socket操作写成了一个类ctrl,然后我想在程序调用时ctrl c = new ctrl(); c.openClient();来打开连接,然后调用
c.send(); 进行数据发送,请问这样为何不行?
class ctrl
{
#region socket操作
private int port = 2000;
// ManualResetEvent instances signal completion.
private ManualResetEvent connectDone =
new ManualResetEvent(false);
private ManualResetEvent sendDone =
new ManualResetEvent(false);
private ManualResetEvent receiveDone =
new ManualResetEvent(false);
Socket client; // The response from the remote device.
private static String response = String.Empty; public bool openClient()
{
try
{
IPHostEntry ipHostInfo = Dns.Resolve("localhost");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket.
client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp); // Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne(); return true; }
catch (Exception e)
{ GlobalApp.loger.Error("openClient", e);
return false;
}
} private void closeClient()
{
if (client.Connected)
{
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
}
} private void ConnectCallback(IAsyncResult ar)
{
try
{
// Complete the connection.
client.EndConnect(ar); // Signal that the connection has been made.
connectDone.Set(); Receive(client);
}
catch (Exception e)
{
connectDone.Set();
GlobalApp.loger.Error("ConnectCallback", e);
}
} private void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client; // Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
GlobalApp.loger.Error("Receive", e);
}
} private void ReceiveCallback(IAsyncResult ar)
{ }
public void Send(String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data); this.client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), this.client);
} private 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); // Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception ex)
{
GlobalApp.loger.Error("SendCallback失败", ex);
sendDone.Set(); }
} #endregion
}
c.send(); 进行数据发送,请问这样为何不行?
class ctrl
{
#region socket操作
private int port = 2000;
// ManualResetEvent instances signal completion.
private ManualResetEvent connectDone =
new ManualResetEvent(false);
private ManualResetEvent sendDone =
new ManualResetEvent(false);
private ManualResetEvent receiveDone =
new ManualResetEvent(false);
Socket client; // The response from the remote device.
private static String response = String.Empty; public bool openClient()
{
try
{
IPHostEntry ipHostInfo = Dns.Resolve("localhost");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket.
client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp); // Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne(); return true; }
catch (Exception e)
{ GlobalApp.loger.Error("openClient", e);
return false;
}
} private void closeClient()
{
if (client.Connected)
{
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
}
} private void ConnectCallback(IAsyncResult ar)
{
try
{
// Complete the connection.
client.EndConnect(ar); // Signal that the connection has been made.
connectDone.Set(); Receive(client);
}
catch (Exception e)
{
connectDone.Set();
GlobalApp.loger.Error("ConnectCallback", e);
}
} private void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client; // Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
GlobalApp.loger.Error("Receive", e);
}
} private void ReceiveCallback(IAsyncResult ar)
{ }
public void Send(String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data); this.client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), this.client);
} private 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); // Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception ex)
{
GlobalApp.loger.Error("SendCallback失败", ex);
sendDone.Set(); }
} #endregion
}
调用的代码:
private void btnSet_Click(object sender, EventArgs e)
{
ctrl c = new ctrl();
if (c.openClient())
{
MessageBox.Show("success");
c.Send("aaa");
}
else
MessageBox.Show("fail");
}出现的问题:
由于套接字没有连接并且(当使用一个 sendto 调用发送数据报套接字时)没有提供地址,发送或接收数据的请求没有被接受。位置:
this.client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), this.client);谢谢
附段监听代码
public void BeginListen()
{
IPHostEntry ipHostInfo = Dns.Resolve("localhost");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); byte[] byteMessage = new byte[100];
server.Bind(remoteEP); // do while (true)
{ try
{ server.Listen(5); Socket newSocket = server.Accept(); newSocket.Receive(byteMessage); string sTime = DateTime.Now.ToShortTimeString(); string msg = sTime + ":" + "Message from:"; msg += newSocket.RemoteEndPoint.ToString() + Encoding.Default.GetString(byteMessage); // this.listBox1.Items.Add(msg);
}
catch (Exception ex)
{ } }}
然后先new个thread来开启监听,我试了好像就可以了