using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace TcpClientClass
{
public class ReadObject
{
//public Socket workSoket =null;
public int bytesize = 256;
public byte[] bytes;
public NetworkStream netStream;
public ReadObject(NetworkStream ns, int size)
{
bytesize = size;
bytes = new byte[bytesize];
netStream = ns;
}
}
class ConnectToServer
{
private TcpClient client;
private EventWaitHandle allDone = new EventWaitHandle(false, EventResetMode.ManualReset);
private NetworkStream ns;
private DateTime timer;
private bool isExit = false;
public void ConnectTo(IPAddress ip, int port)
{
client = new TcpClient(AddressFamily.InterNetwork);
try
{
timer = DateTime.Now;
allDone.Reset();
client.BeginConnect(ip, port, RequestCallback, client);
if (!allDone.WaitOne(2000, false))
{
client.Close();
throw new SocketException(10060);
}
}
catch (Exception e1)
{
Console.WriteLine(e1.Message);
}
}
public void RequestCallback(IAsyncResult ar)
{
allDone.Set();
try
{
client = (TcpClient)ar.AsyncState;
TimeSpan timeduration = DateTime.Now - timer;
Console.WriteLine("连接时间:" + timeduration.TotalSeconds.ToString());
Console.WriteLine("连接成功" + client.Client.RemoteEndPoint.ToString() + "\n");
ns = client.GetStream();
ReadObject readObject = new ReadObject(ns, client.ReceiveBufferSize);
ns.BeginRead(readObject.bytes, 0, readObject.bytes.Length, ReadCallback, readObject);
}
catch (Exception e1)
{
TimeSpan timeduration = DateTime.Now - timer;
Console.WriteLine("连接时间:" + timeduration.TotalSeconds.ToString());
Console.WriteLine(e1.Message);
return;
}
}
public void ReadCallback(IAsyncResult ar)
{
try
{
ReadObject ro = (ReadObject)ar.AsyncState;
int count = ro.netStream.EndRead(ar);
Console.WriteLine("接收到:" + System.Text.Encoding.UTF8.GetString(ro.bytes, 0, count));
if (isExit == false)
{
ro = new ReadObject(ns, client.ReceiveBufferSize);
ns.BeginRead(ro.bytes, 0, ro.bytes.Length, ReadCallback, ro);
}
}
catch (Exception e2)
{
Console.WriteLine(e2.Message);
return;
}
}
private void SendString(string str)
{
try
{
byte[] by = System.Text.Encoding.UTF8.GetBytes(str);
ns.BeginWrite(by, 0, by.Length, new AsyncCallback(SendCallBack), ns);
ns.Flush();
}
catch (Exception e3)
{
Console.WriteLine(e3.Message);
//MessageBox.Show(e3.ToString());
return;
}
}
//发送数据回调的方法
private void SendCallBack(IAsyncResult ar)
{
try
{
ns.EndWrite(ar);
}
catch (Exception e4)
{
Console.WriteLine(e4.Message);
return;
}
}
}
}