【发布时间】:2016-11-05 23:32:49
【问题描述】:
我需要实现 tcp socket Client。我们必须以特定的时间间隔从服务器 tcp 套接字接收数据。如果我们从客户端发出连接请求,则连接不会断开。每当服务器发送数据时,我们都必须接收数据。我尝试过异步客户端通信来自 MSDN 网站。但是Receive回调函数是在receive方法中调用的,所以我们必须无间隔地从服务器接收数据。如果没有连续接收到数据,则连接将进入接收完成并断开连接。
谁能帮帮我...谢谢提前
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Configuration;
using System.Net;
using System.IO;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Transactions;
namespace ClientSocket
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 5176;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousClient
{
public const int port = 8095;
public static ManualResetEvent connectDone =
new ManualResetEvent(false);
public static ManualResetEvent sendDone =
new ManualResetEvent(false);
public static ManualResetEvent receiveDone =
new ManualResetEvent(false);
public static String response = String.Empty;
public static void StartClient()
{
try
{
IPAddress ipAddress = IPAddress.Parse("192.168.1.89");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
//Send(client, Msg + "<EOF>");
//sendDone.WaitOne();
Receive(client);
receiveDone.WaitOne();
MessageBox.Show(response, "Final Response received");
//Send(client, "Data From Client" + "<EOF>");
//sendDone.WaitOne();
//client.Shutdown(SocketShutdown.Both);
//client.Close();
}
catch (SocketException e)
{
MessageBox.Show(e.Message);
}
//finally
//{
// response = string.Empty;
//}
}
public static void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
client.EndConnect(ar);
MessageBox.Show(string.Concat("Socket connected to ",
client.RemoteEndPoint.ToString()));
connectDone.Set();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public static void Receive(Socket client)
{
try
{
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public static void ReceiveCallback(IAsyncResult ar)
{
MessageBox.Show("Receivecallback");
StateObject state = (StateObject)ar.AsyncState;
state.sb.Clear();
Socket client = state.workSocket;
try
{
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
MessageBox.Show(state.sb.ToString(), "Data");
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
//if (state.sb.Length > 1)
//{
// response = state.sb.ToString();
//}
//////Send(client, "NG", "Error");
//receiveDone.Set();
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
//state.sb.Clear();
}
}
catch (Exception e)
{
Send(client, "NG", e.Message.ToString());
MessageBox.Show(e.ToString());
}
}
public static void Send(Socket client, String data, String ErrorMessage)
{
byte[] Status = Encoding.ASCII.GetBytes(data);
byte[] errorMessage = Encoding.ASCII.GetBytes(ErrorMessage);
byte[] statusSize = new byte[240];
int i = new int();
foreach (var ST in Status)
{
i++;
if (i == 1)
statusSize[0] = ST;
if (i == 2)
statusSize[1] = ST;
}
if (data.Equals("NG"))
{
int j = 2;
foreach (byte em in errorMessage)
{
statusSize[j] = em;
j++;
}
}
client.BeginSend(statusSize, 0, statusSize.Length, 0,
new AsyncCallback(SendCallback), client);
}
public static void SendCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
int bytesSent = client.EndSend(ar);
MessageBox.Show(string.Concat("Sent bytes to server.", bytesSent.ToString()));
//SocketConnected(client);
sendDone.Set();
//MessageBox.Show("Send Callback");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public static bool SocketConnected(Socket s)
{
bool part1 = s.Poll(1000, SelectMode.SelectRead);
bool part2 = (s.Available == 0);
if (part1 && part2)
return false;
else
return true;
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
AsynchronousClient.StartClient();
}
}
}
}
【问题讨论】:
-
我猜你已经开始实现这样的间隔例程了。你会介意张贴吗?这将是一个很好的起点。
-
我附上了我的代码。它只收到第一个响应。如果服务器在一段时间后发送数据,那么我如何从这个代码中获取数据。
-
任何人都可以根据上面的代码帮助我
标签: c# sockets tcpclient windows-applications