string TcpConnect(string message, string hostNameOrAddress, string port)
{
Cursor.Current = Cursors.WaitCursor;
Cursor.Show();
bool IsNumber = true;
foreach (char c in port)
{
IsNumber = Char.IsNumber(c);
if (!IsNumber)
break;
}
if (!IsNumber)
{
Cursor.Current = Cursors.Default;
Cursor.Hide();
return "S";
}
//throw new ArgumentException("Port must be \"Number\"!!");
Encoding encode = Encoding.ASCII;
TcpClient client = new TcpClient(AddressFamily.InterNetwork);
client.Client.Poll(2000, SelectMode.SelectError);
client.Client.Poll(2000, SelectMode.SelectRead);
client.Client.Poll(2000, SelectMode.SelectWrite);
NetworkStream stream = null;
ArrayList buffer = null;
Char splitchar = '^';
try
{
IPEndPoint point = new IPEndPoint(Dns.GetHostEntry(hostNameOrAddress).AddressList[0], int.Parse(port));
client.Connect(point);
stream = client.GetStream();
string sentdata = String.Format("{1}{0}{2}", splitchar.ToString(), message.Length, message);
buffer = new ArrayList(encode.GetBytes(sentdata));
stream.WriteByte(1);
stream.Write((byte[])buffer.ToArray(typeof(System.Byte)), 0, buffer.Count);
stream.WriteByte(2);
int iTimeOut = 2000;
while (client.Client.Available == 0 && !stream.DataAvailable)
{
if (iTimeOut == 0)
break;
Thread.Sleep(1);
iTimeOut--;
}
buffer.Clear();
int i = stream.ReadByte();
while (i > -1)
{
if (i == 1)
buffer.Clear();
else if (i == 2)
break;
else
buffer.Add((byte)i);
i = stream.ReadByte();
}
}
catch (SocketException)
{
if (errCount == 3)
{
//SharedMethod.NextAddr = !SharedMethod.NextAddr;
errCount = 1;
}
else
{
errCount++;
}
Cursor.Current = Cursors.Default;
Cursor.Hide();
return "S";
}
catch (Exception)
{
Cursor.Current = Cursors.Default;
Cursor.Hide();
return "G";
}
finally
{
if (stream != null)
stream.Close();
if (client != null)
client.Close();
}
if (buffer != null && buffer.Count > 0)
{
byte[] rbyte = (byte[])buffer.ToArray(typeof(System.Byte));
string result = encode.GetString(rbyte, 0, rbyte.Length);
if (String.IsNullOrEmpty(result) || result.IndexOf(splitchar) < 0)
{
Cursor.Current = Cursors.Default;
Cursor.Hide();
return "R";
//throw new InvalidOperationException("Receive data struct incurrect!!...");
}
else
{
string slength = result.Substring(0, result.IndexOf(splitchar));
int datalength = 0;
try
{
datalength = int.Parse(slength);
}
catch
{
Cursor.Current = Cursors.Default;
Cursor.Hide();
return "R";
//throw new InvalidOperationException("LEN must be \"Number\"!!");
}
if (datalength == result.Length - slength.Length - 1)
{
Cursor.Current = Cursors.Default;
Cursor.Hide();
return result.Substring(slength.Length + 1);
}
else
{
Cursor.Current = Cursors.Default;
Cursor.Hide();
return "R";
}
//throw new InvalidOperationException("Data lost!!");
}
}
else
{
Cursor.Current = Cursors.Default;
Cursor.Hide();
return "G";
}
}
沒有留言:
張貼留言