using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PiCalendar
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.bgw1.WorkerSupportsCancellation = true;
this.bgw1.RunWorkerAsync();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (this.bgw1.IsBusy)
{
this.bgw1.CancelAsync();
}
}
private void bgw1_DoWork(object sender, DoWorkEventArgs e)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
string data = null;
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 62000);
// Create a TCP/IP socket.
Socket client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
client.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("hello\r\n");
// Send the data through the socket.
int bytesSent = client.Send(msg);
int cnt = 0;
while (true)
{
if (this.bgw1.CancellationPending)
{
break;
}
bytes = new byte[4096];
int bytesRec = client.Receive(bytes);
data += Encoding.UTF8.GetString(bytes, 0, bytesRec);
if (data.IndexOf("\r\n") > -1)
{
if (data == "quit")
{
break;
}
cnt++;
if (this.InvokeRequired)
{
this.richTextBox1.Invoke(new Action(delegate ()
{
if (cnt == 50)
{
this.richTextBox1.ResetText();
cnt = 0;
}
this.richTextBox1.AppendText(data);
this.richTextBox1.ScrollToCaret();
}));
}
data = string.Empty;
}
}
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception ex)
{
Console.WriteLine("Unexpected exception : {0}", ex.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void bgw1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("bgw1 completed");
}
}
}
댓글 없음:
댓글 쓰기