C/S 架构的简单Socket 通信的例子
新建两个Form程序
引用命名空间:using System.Net; using System.Net.Sockets; Server 端:
放两个Button和两个TextBox public partial class Form1 : Form {
Socket s = null; IPEndPoint iep = null; byte[] buf = new byte[1024]; Socket worker = null;
public Form1() {
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false; }
private void button1_Click(object sender,EventArgs e) {
//创建一个通道
s = new
Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //创建一个侦听点
iep = new IPEndPoint(IPAddress.Any,20000); //绑定到通道上 s.Bind(iep); //侦听 s.Listen(6); //通过异步来处理
s.BeginAccept(new AsyncCallback(Accept),s); this.button1.Visable = false; }
void Accept(IAsyncResult ia) {
s = ia.AsyncState as Socket; worker = s.EndAccept();
s.BeginAccept(new AsyncCallback(Accept),s); try {
worker.BeginReceive(buf,0,buf.Length,Socket.Flogs.None, new AsyncCallback(Receive),worker); } catch { throw ;} }
void Receive(IAsyncResult ia) {
worker = ia.AsyncState as Socket; int count = worker.EndReceive(ia);
worker.BeginReceive(buf,0,buf.Length,Socket.Flogs.None,new AsyncCallback(Receive),worker);
string context = Encoding.GetEncoding(\ this.textbox1.text += Environment.NewLine; this.textbox1.text += context; }
private void button2_Click(object sender, EventArgs e) {
string context =\ if(context != \ {
this.textbox1.Text += Environment.NewLine; this.textbox1.Text += context; this.textbox2.Text = \
worker.Send(Encoding.GetEncoding(\ } } } 客户端: 主要代码:
public partial class Form1 : Form {
Socket s = null; IPEndPoint iep = null; byte[] buf = new byte[1024];
public Form1() {
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false; }
private void button1_Click(object sender,EventArgs e) {
s = new
Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); iep = new IPEndPoint(IPAddress.Parse(\ try {
s.Connect(iep);
this.label1.Text = \连接成功\ this.button1.Visable =false; } catch { throw ;} }
private void button2_Click(object sender, EventArgs e)
{
string context = iep.ToString() + \ if(context != \ {
this.textbox1.Text += Environment.NewLine; this.textbox1.Text += context; this.tetxbox2.Text =\
s.Send(Encoding.GetEncoding(\ try {
s.BeginReceive(buf,0,buf.Length,Socket.Flogs.None, new AsyncCallback(Receive),s); } catch { throw ;} } }
void Receive(IAsynvResult ia) {
s = ia.AsyncState as Socket; int count = s.EndReceive(ia);
s.BeginReceive(buf,0,buf.Length,Socket.Flogs.None, new AsyncCallback(Receive),s);
string context =Encoding.GetEncoding(\ this.textbox1.Text += Environment.NewLine; this.textbox1.Text += context; } }
百度搜索“77cn”或“免费范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,免费范文网,提供经典小说综合文库C S 架构的简单Socket 通信的例子在线全文阅读。
相关推荐: