PHP Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
public class TCPClient
{
#region Declarings
TcpClient Client = new TcpClient();
NetworkStream netStream;
#endregion
public Boolean Connect(String IP, Int32 Port)
{
try
{
Client.Connect(IP, Port);
if (Client.Connected)
{
netStream = Client.GetStream();
return true;
}
}
catch { }
return false;
}
public void Disconnect()
{
Client.Close();
}
public Boolean Connected()
{
return Client.Connected;
}
public String GetData()
{
try
{
StringBuilder Builder = new StringBuilder();
Byte[] Bytes = new Byte[1024];
Int32 tBytes = 0;
if (netStream.DataAvailable)
{
tBytes = netStream.Read(Bytes, 0, Bytes.Length);
Builder.AppendFormat("{0}", Encoding.UTF8.GetString(Bytes, 0, tBytes));
netStream.Flush();
return Builder.ToString();
}
}
catch (Exception ex)
{
return ex.Message;
}
return null;
}
public void SendData(String Data)
{
try
{
if (netStream.CanWrite)
{
Byte[] Bytes = Encoding.ASCII.GetBytes(Data);
netStream.Write(Bytes, 0, Bytes.Length);
}
}
catch { }
}
}
public class TCPServer
{
#region
TcpListener Listener;
TcpClient Server = new TcpClient();
NetworkStream netStream;
#endregion
public Boolean Connected()
{
return Server.Connected;
}
public TCPServer(Int32 Port)
{
Listener = new TcpListener(Port);
Listener.Start();
}
private void Listening()
{
for (; true; )
{
Server = Listener.AcceptTcpClient();
if (Server.Connected)
{
netStream = Server.GetStream();
break;
}
}
}
public void Listen()
{
Thread thread = new Thread(Listening);
thread.Start();
}
public String GetData()
{
try
{
StringBuilder Builder = new StringBuilder();
Byte[] Bytes = new Byte[1024];
Int32 tBytes = 0;
if (netStream.DataAvailable)
{
tBytes = netStream.Read(Bytes, 0, Bytes.Length);
Builder.AppendFormat("{0}", Encoding.UTF8.GetString(Bytes, 0, tBytes));
netStream.Flush();
return Builder.ToString();
}
}
catch (Exception ex)
{
return ex.Message;
}
return null;
}
public void SendData(String Data)
{
try
{
if (netStream.CanWrite)
{
Byte[] Bytes = Encoding.UTF8.GetBytes(Data);
netStream.Write(Bytes, 0, Bytes.Length);
}
}
catch { }
}
public void Disconnect()
{
Server.Close();
}
}
Results 1 to 1 of 1
Thread: [C#] TCP Class
- 25 Nov. 2010 10:28pm #1
[C#] TCP Class