C# socket编程异步服务端同步客户端.docx
- 文档编号:7513148
- 上传时间:2023-01-24
- 格式:DOCX
- 页数:13
- 大小:17.54KB
C# socket编程异步服务端同步客户端.docx
《C# socket编程异步服务端同步客户端.docx》由会员分享,可在线阅读,更多相关《C# socket编程异步服务端同步客户端.docx(13页珍藏版)》请在冰豆网上搜索。
C#socket编程异步服务端同步客户端
C#socket编程异步服务端同步客户端
程序运行界面如下:
托盘里的菜单如下:
c#作为微软.Net战略的重要棋子,对网络编程提供了很好的支持和优化。
实现起来特别方便,还是看代码吧,已经注释的很清楚了。
代码如下:
usingSystem;
usingSystem.Drawing;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Windows.Forms;
usingSystem.Data;
usingSystem.IO;
usingSystem.Net.Sockets;
usingSystem.Threading;
namespacep2pChat
}
#endregion
///
///应用程序的主入口点。
///
[STAThread]
staticvoidMain()
{
Application.Run(newMainForm());
}
//开始监听
privatevoidListen()
{
try
{
tcpLister.Start();
while(true)
{
Sockets=tcpLister.AcceptSocket();
Byte[]stream=newByte[80];
inti=s.Receive(stream);
stringmessage=System.Text.Encoding.UTF8.GetString(stream);
this.txtRecord.AppendText(message);
}
}
catch(System.Security.SecurityException)
{
MessageBox.Show("防火墙安全错误!
","错误",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
catch(System.Exception)
{
//this.txtRecord.AppendText("已停止监听!
");
}
}
privatevoidabortLister(objectsender,System.ComponentModel.CancelEventArgse)
{
this.tcpLister.Stop();
}
//发送
privatevoidbtnSend_Click(objectsender,System.EventArgse)
{
if(this.txtContent.Text=="")
{
MessageBox.Show("不能发送空信息!
","提示",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
else
{
this.Send();
}
}
//发送消息
privatevoidSend()
{
try
{
stringmsg=this.txtName.Text+"("+System.DateTime.Now.ToString()+")"+this.txtContent.Text+"";
TcpClientclient=newTcpClient(this.txtIp.Text,5566);
NetworkStreamsendStream=client.GetStream();
StreamWriterwriter=newStreamWriter(sendStream);
writer.Write(msg);
writer.Flush();
sendStream.Close();
client.Close();
this.txtRecord.AppendText(msg);
this.txtContent.Clear();
}
catch(System.Exception)
{
this.txtRecord.AppendText("目标计算机拒绝连接请求!
");
}
}
privatevoidMainForm_Load(objectsender,System.EventArgse)
{
this.txtRecord.AppendText("正在监听...");
lister.Name="监听本地端口";
lister.Start();
}
}
}
{
///
///MainForm的摘要说明。
///
publicclassMainForm:
System.Windows.Forms.Form
{
privateSystem.Windows.Forms.Labellabel1;
privateSystem.Windows.Forms.Labellabel2;
privateSystem.Windows.Forms.TextBoxtxtIp;
privateSystem.Windows.Forms.TextBoxtxtRecord;
privateSystem.Windows.Forms.TextBoxtxtName;
privateSystem.Windows.Forms.ButtonbtnSend;
privateSystem.Windows.Forms.TextBoxtxtContent;
privateTcpListenertcpLister=newTcpListener(5566);
System.Threading.ThreadStartlistenPort;
System.Threading.Threadlister;
privateSystem.Windows.Forms.Labellabel3;
System.Windows.Forms.NotifyIconNotifyIcon1;
//托盘里显示的图标,我用的是QQ里的宠物狗的图标
privateIconimg=newIcon(@"C:
\OpenPet.ico");
System.Windows.Forms.ContextMenunMenu;
///
///必需的设计器变量。
///
privateSystem.ComponentModel.Containercomponents=null;
publicMainForm()
{
//
//Windows窗体设计器支持所必需的
//
InitializeComponent();
//不显示最大化按钮
this.MaximizeBox=false;
//最小化时不显示在任务栏
this.ShowInTaskbar=false;
listenPort+=newThreadStart(this.Listen);
lister=newThread(listenPort);
this.Closing+=newSystem.ComponentModel.CancelEventHandler(abortLister);
Initializenotifyicon();
//
//TODO:
在InitializeComponent调用后添加任何构造函数代码
//
}
#region初始化托盘组件
privatevoidInitializenotifyicon()
{
NotifyIcon1=newNotifyIcon();
NotifyIcon1.Icon=img;
NotifyIcon1.Text="局域网聊天程序";
NotifyIcon1.Visible=true;
NotifyIcon1.DoubleClick+=newEventHandler(this.showMainForm);
MenuItem[]menuArray=newMenuItem[3];
menuArray[0]=newMenuItem();
menuArray[0].Text="显示主窗口";
menuArray[0].Click+=newEventHandler(this.showMainForm);
menuArray[0].DefaultItem=true;
menuArray[1]=newMenuItem("-");
menuArray[2]=newMenuItem();
menuArray[2].Text="退出";
menuArray[2].Click+=newEventHandler(this.exitSystem);
nMenu=newContextMenu(menuArray);
NotifyIcon1.ContextMenu=nMenu;
}
//显示主窗口
privatevoidshowMainForm(objectsender,System.EventArgse)
{
this.WindowState=System.Windows.Forms.FormWindowState.Normal;
}
//退出程序
privatevoidexitSystem(objectsender,System.EventArgse)
{
NotifyIcon1.Visible=false;
this.Close();
}
#endregion
///
///清理所有正在使用的资源。
///
protectedoverridevoidDispose(booldisposing)
{
if(disposing)
{
if(components!
=null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#regionWindows窗体设计器生成的代码
///
///设计器支持所需的方法-不要使用代码编辑器修改
///此方法的内容。
///
privatevoidInitializeComponent()
{
this.label1=newSystem.Windows.Forms.Label();
this.txtIp=newSystem.Windows.Forms.TextBox();
this.txtRecord=newSystem.Windows.Forms.TextBox();
this.label2=newSystem.Windows.Forms.Label();
this.txtName=newSystem.Windows.Forms.TextBox();
this.btnSend=newSystem.Windows.Forms.Button();
this.txtContent=newSystem.Windows.Forms.TextBox();
this.label3=newSystem.Windows.Forms.Label();
this.SuspendLayout();
//
//label1
//
this.label1.Location=newSystem.Drawing.Point(16,232);
this.label1.Name="label1";
this.label1.Size=newSystem.Drawing.Size(72,23);
this.label1.TabIndex=0;
this.label1.Text="目标地址:
";
this.label1.TextAlign=System.Drawing.ContentAlignment.MiddleCenter;
//
//txtIp
//
this.txtIp.Anchor=((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left|System.Windows.Forms.AnchorStyles.Right)));
this.txtIp.Location=newSystem.Drawing.Point(80,232);
this.txtIp.Name="txtIp";
this.txtIp.Size=newSystem.Drawing.Size(200,21);
this.txtIp.TabIndex=1;
this.txtIp.Text="";
//
//txtRecord
//
this.txtRecord.Anchor=((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left|System.Windows.Forms.AnchorStyles.Right)));
this.txtRecord.Location=newSystem.Drawing.Point(16,32);
this.txtRecord.Multiline=true;
this.txtRecord.Name="txtRecord";
this.txtRecord.ReadOnly=true;
this.txtRecord.ScrollBars=System.Windows.Forms.ScrollBars.Vertical;
this.txtRecord.Size=newSystem.Drawing.Size(264,176);
this.txtRecord.TabIndex=4;
this.txtRecord.Text="";
//
//label2
//
this.label2.Location=newSystem.Drawing.Point(24,256);
this.label2.Name="label2";
this.label2.Size=newSystem.Drawing.Size(48,23);
this.label2.TabIndex=5;
this.label2.Text="呢称:
";
this.label2.TextAlign=System.Drawing.ContentAlignment.MiddleCenter;
//
//txtName
//
this.txtName.Location=newSystem.Drawing.Point(80,256);
this.txtName.Name="txtName";
this.txtName.Size=newSystem.Drawing.Size(88,21);
this.txtName.TabIndex=6;
this.txtName.Text="";
//
//btnSend
//
this.btnSend.Location=newSystem.Drawing.Point(200,256);
this.btnSend.Name="btnSend";
this.btnSend.Size=newSystem.Drawing.Size(64,23);
this.btnSend.TabIndex=0;
this.btnSend.Text="发送";
this.btnSend.Click+=newSystem.EventHandler(this.btnSend_Click);
//
//txtContent
//
this.txtContent.Anchor=((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom|System.Windows.Forms.AnchorStyles.Left)
|System.Windows.Forms.AnchorStyles.Right)));
this.txtContent.Location=newSystem.Drawing.Point(16,288);
this.txtContent.Multiline=true;
this.txtContent.Name="txtContent";
this.txtContent.Size=newSystem.Drawing.Size(264,152);
this.txtContent.TabIndex=8;
this.txtContent.Text="";
//
//label3
//
this.label3.Anchor=((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top|System.Windows.Forms.AnchorStyles.Left)
|System.Windows.Forms.AnchorStyles.Right)));
this.label3.Location=newSystem.Drawing.Point(16,8);
this.label3.Name="label3";
this.label3.Size=newSystem.Drawing.Size(100,16);
this.label3.TabIndex=9;
this.label3.Text="聊天记录:
";
this.label3.TextAlign=System.Drawing.ContentAlignment.MiddleLeft;
//
//MainForm
//
this.AutoScaleBaseSize=newSystem.Drawing.Size(6,14);
this.ClientSize=newSystem.Drawing.Size(292,453);
this.Controls.Add(this.label3);
this.Controls.Add(this.txtContent);
this.Controls.Add(this.btnSend);
this.Controls.Add(this.txtName);
this.Controls.Add(this.label2);
this.Controls.Add(this.txtRecord);
this.Controls.Add(this.txtIp);
this.Controls.Add(this.label1);
this.Name="MainForm";
this.Text="局域网聊天程序";
this.Load+=newSystem.EventHandler(this.MainForm_Load);
this.ResumeLayout(false);
}
#endregion
///
///应用程序的主入口点。
///
[STAThread]
staticvoidMain()
{
Application.Run(newMainForm());
}
//开始监听
privatevoidListen()
{
try
{
tcpLister.Start();
while(true)
{
Sockets=tcpLister.AcceptSocket();
Byte[]stream=newByte[80];
inti=s.Receive(stream);
stringmessage=System.Text.Encoding.UTF8.GetString(stream);
this.txtRecord.AppendText(message);
}
}
catch(System.Security.SecurityException)
{
MessageBox.Show("防火墙安全错误!
","错误",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
catch(System.Exception)
{
//this.txtRecord.AppendText("已停止监听!
");
}
}
privatevoidabortLister(objectsender,System.ComponentModel.CancelEventArgse)
{
this.tcpLister.Stop();
}
//发送
privatevoidbtnSend_Click(objectsender,System.EventArgse)
{
if(this.txtContent.Text=="")
{
MessageBox.Show("不能发送空信息!
","提示",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
else
{
this.Send();
}
}
//发送消息
privatevoidSend()
{
try
{
stringmsg=this.txtName.Text+"("+System.DateTime.Now.ToString()+")"+this.txtContent.Text+"";
TcpClientclient=newTcpClient(this.txtIp.Text,5566);
NetworkStreamsendStream=client.GetStream();
StreamWriterwriter=newStreamWriter(sendStream);
writer.Write(msg);
writer.Flush();
sendStream.Close();
client.Close();
this.txtRecord.AppendText(msg);
this.txtContent.Clear();
}
catch(System.Exception)
{
this.txtRecord.AppendText("目标计算机拒绝连接请求!
");
}
}
privatevoidMainForm_Load(objectsender,System.EventArgse)
{
this.txtRecord.AppendText("正在监听...");
lister.Name="监听本地端口";
lister.Start();
}
}
}
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- C# socket编程异步服务端同步客户端 socket 编程 异步 服务端 同步 客户端
![提示](https://static.bdocx.com/images/bang_tan.gif)