C# TCP Client
class CTcpClient
{
TcpClient client;
NetworkStream stream;
private Thread m_ListenThread;
string serverIP;
string tvID;
public delegate void OnMessageDele(string message);
public event OnMessageDele OnMessage;
public CTcpClient()
{
}
public void Connect(string serverIP, string tvID)
{
this.serverIP = serverIP;
this.tvID = tvID;
m_ListenThread = new Thread(ConnectTCP);
m_ListenThread.Start();
}
private void ConnectTCP()
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 13000;
//string server = "127.0.0.1";
//string tvID = "abc1";
client = new TcpClient(serverIP, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(tvID);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
//Console.WriteLine("Sent: {0}", message);
byte[] message = new byte[client.ReceiveBufferSize];
int byteRead;
while (true)
{
byteRead = 0;
try
{
byteRead = stream.Read(message, 0, client.ReceiveBufferSize);
}
catch
{
break;
}
if (byteRead == 0)
{
break;
}
string receiveMessage = System.Text.ASCIIEncoding.GetEncoding("euc-kr").GetString(message, 0, byteRead);
Console.WriteLine(receiveMessage);
if (OnMessage != null)
{
OnMessage(receiveMessage);
}
}
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
}
public void Disconnect()
{
// Close everything.
if (stream != null)
{
stream.Close();
}
if (client != null)
{
client.Close();
}
if (m_ListenThread != null)
{
m_ListenThread.Abort();
}
}
}
'C# > Network' 카테고리의 다른 글
C# Http Post File Upload (0) | 2020.08.14 |
---|---|
C# Multi Thread TcpServer (0) | 2020.08.14 |
C# TCPServer with WebSocket (0) | 2020.08.13 |
C# UDP (0) | 2020.08.13 |
C# WOL 컴퓨터 원격 온오프 (0) | 2020.08.07 |