C S 架构的简单Socket 通信的例子

2018-12-21 11:41

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; } }


C S 架构的简单Socket 通信的例子.doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:重庆大学生物化学真题02-05

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: