public static void sendData()
{
while (true)
{
Console.WriteLine("send to client\n");
//服务端给客户端回送消息
string strSend = "Hello Android Client!" + DateTime.Now.Second;
//string strSend = "HelloClient1HelloClient2HelloClient3HelloClient4HelloClient5HelloClient6HelloClient7HelloClient8HelloClient9HelloClient10HelloClient11HelloClien12HelloClien13HelloClien14HelloClien15HelloClient16";
byte[] sendByte = new byte[1024];
//将发送的字符串转换为byte[]
sendByte = UTF8Encoding.UTF8.GetBytes(strSend);
//服务端发送数据
serverSocket.Send(sendByte, sendByte.Length, 0);
Thread.Sleep(1000);
}
}
#region
/// <summary>
/// 异步连接
/// </summary>
/// <param></param>
/// <param></param>
/// <param></param>
public static void Connect(IPAddress ip, int port)
{
serverSocket.BeginConnect(ip, port, new AsyncCallback(ConnectCallback), serverSocket);
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
handler.EndConnect(ar);
}
catch (SocketException ex)
{
throw ex;
}
}
/// <summary>
/// 发送数据
/// </summary>
/// <param></param>
public static void Send(string data)
{
//Send(System.Text.Encoding.UTF8.GetBytes(data));
Send(UTF8Encoding.UTF8.GetBytes(data));
}
/// <summary>
/// 发送数据
/// </summary>
/// <param></param>
private static void Send(byte[] byteData)
{
try
{
int length = byteData.Length;
byte[] head = BitConverter.GetBytes(length);
byte[] data = new byte[head.Length + byteData.Length];
Array.Copy(head, data, head.Length);
Array.Copy(byteData, 0, data, head.Length, byteData.Length);
serverSocket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), serverSocket);
}
catch (SocketException ex)
{ }
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
handler.EndSend(ar);
}
catch (SocketException ex)
{
throw ex;
}
}
static byte[] MsgBuffer = new byte[128];