一个C#Socket通信小例子
一个C#Socket通信小例子
2010年11月05日
//服务端
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace Service
{
public partial class Service : Form
{
public Service()
{
InitializeComponent();
}
Socket handler;
private void Service_Load(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(Listen));
thread.Start();
}
private void Listen()
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
Socket listener = new Socket(
AddressFamily.InterNetworkV6,
SocketType.Stream,
ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
byte[] bytes = new byte[1024];
SetTextDelegate("Waiting for a connection...");
handler = listener.Accept();
int bytesRec = handler.Receive(bytes);
string data = Encoding.ASCII.GetString(bytes, 0, bytesRec);
SetTextDelegate("receive time:" + DateTime.Now.ToString("HH:mm:ss") + data);
byte[] msg = Encoding.ASCII.GetBytes(data);
//handler.Send(msg);
}
}
void SetText(string str)
{
textBox1.Text += (Environment.NewLine + str);
}
void SetTextDelegate(string str)
{
BeginInvoke(new SetTextHandler(SetText), str);
}
private void Service_FormClosed(object sender, FormClosedEventArgs e)
{
handler.Shutdown(SocketShutdown.Both);
handler.Close();
Environment.Exit(0);
}
}
public delegate void SetTextHandler(string str);
}
//客户端
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace SocketApp
{
public partial class Client : Form
{
public Client()
{
InitializeComponent();
}
public void StartClient()
{
byte[] bytes = new byte[1024];
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
Socket sender = new Socket(
AddressFamily.InterNetworkV6,
SocketType.Stream,
ProtocolType.Tcp);
sender.Connect(remoteEP);
byte[] msg = Encoding.ASCII.GetBytes("send time:" + DateTime.Now.ToString("HH:mm:ss") + " MessageContent:" + textBox1.Text.Trim());
int bytesSend = sender.Send(msg);
//int bytesRec = sender.Receive(bytes);
//textBox1.Text +=
// ("/r Echoed test = " + Encoding.ASCII.GetString(bytes, 0, bytesRec));
sender.Shutdown(SocketShutdown.Both);
sender.Close();
textBox1.Text = string.Empty;
}
private void button1_Click(object sender, EventArgs e)
{
StartClient();
}
}
}
//参考 http://www.cnblogs.com/zhangpengshou/archive/2008/09/16/1292085.html