C# socket beginAccept
服务端:
需要增加的命名空间:
using System.Threading;
using System.Net;
using System.Net.Sockets;
以下是具体实现。
C# code复制代码
namespace TCPServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public bool btnstatu = true; //开始停止服务按钮状态
public Thread myThread; //声明一个线程实例
public Socket newsock; //声明一个Socket实例
public Socket Client;
public IPEndPoint localEP;
public int localPort;
public bool m_Listening;
//用来设置服务端监听的端口号
public int setPort
{
get { return localPort; }
set { localPort = value; }
}
//用来往richtextbox框中显示消息
public void showClientMsg(string msg)
{
showClientMsg(msg+"\r\n");
}
//监听函数
public void Listen()
{ //设置端口
setPort=int.Parse(serverport.Text.Trim());
//初始化SOCKET实例
newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//初始化终结点实例
localEP=new IPEndPoint(IPAddress.Any,setPort);
try
{
//绑定
newsock.Bind(localEP);
//监听
newsock.Listen(10);
//用于设置按钮状态
m_Listening = true;
//开始接受连接,异步。
newsock.BeginAccept(new AsyncCallback(OnConnectRequest), newsock);
}
catch (Exception ex)
{
showClientMsg(ex.Message);
}
}
//当有客户端连接时的处理
public void OnConnectRequest(IAsyncResult ar)
{
//初始化一个SOCKET,用于其它客户端的连接
Socket server1 = (Socket)ar.AsyncState;
Client = server1.EndAccept(ar);
//将要发送给连接上来的客户端的提示字符串
string strDateLine = "Welcome here";
Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes(strDateLine);
//将提示信息发送给客户端
Client.Send(byteDateLine, byteDateLine.Length, 0);
//等待新的客户端连接
server1.BeginAccept(new AsyncCallback(OnConnectRequest), server1);
while (true)
{
int recv = Client.Receive(byteDateLine);
string stringdata = Encoding.ASCII.GetString(byteDateLine, 0, recv);
DateTimeOffset now = DateTimeOffset.Now;
//获取客户端的IP和端口
string ip = Client.RemoteEndPoint.ToString();
if (stringdata == "STOP")
{
//当客户端终止连接时
showinfo.AppendText(ip+"已从服务器断开");
break;
}
//显示客户端发送过来的信息
showinfo.AppendText(ip + " " + now.ToString("G") + " " + stringdata + "\r\n");
}
}
//开始停止服务按钮
private void startService_Click(object sender, EventArgs e)
{
//新建一个委托线程
ThreadStart myThreadDelegate = new ThreadStart(Listen);
//实例化新线程
myThread = new Thread(myThreadDelegate);
if (btnstatu)
{
myThread.Start();
statuBar.Text = "服务已启动,等待客户端连接";
btnstatu = false;
startService.Text = "停止服务";
}
else
{
//停止服务(功能还有问题,无法停止)
m_Listening = false;
newsock.Close();
myThread.Abort();
showClientMsg("服务器停止服务");
btnstatu = true;
startService.Text = "开始服务";
statuBar.Text = "服务已停止";
m_Listening = false;
}
}
//窗口关闭时中止线程。
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (myThread != null)
{
myThread.Abort();
}
}
}
}
客户端:
C# code复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace TCPClient
{
public partial class Form1 : Form
{
public Socket newclient;
public bool Connected;
public Thread myThread;
public delegate void MyInvoke(string str);
public Form1()
{
InitializeComponent();
}
public void Connect()
{
byte[] data = new byte[1024];
newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
string ipadd = serverIP.Text.Trim();
int port = Convert.ToInt32(serverPort.Text.Trim());
IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port);
try
{
newclient.Connect(ie);
connect.Enabled = false;
Connected = true;
}
catch(SocketException e)
{
MessageBox.Show("连接服务器失败 "+e.Message);
return;
}
ThreadStart myThreaddelegate = new ThreadStart(ReceiveMsg);
myThread = new Thread(myThreaddelegate);
myThread.Start();
}
public void ReceiveMsg()
{
while (true)
{
byte[] data = new byte[1024];
int recv = newclient.Receive(data);
string stringdata = Encoding.UTF8.GetString(data, 0, recv);
showMsg(stringdata + "\r\n");
//receiveMsg.AppendText(stringdata + "\r\n");
}
}
public void showMsg(string msg)
{
{
//在线程里以安全方式调用控件
if (receiveMsg.InvokeRequired)
{
MyInvoke _myinvoke = new MyInvoke(showMsg);
receiveMsg.Invoke(_myinvoke, new object[] { msg });
}
else
{
receiveMsg.AppendText(msg);
}
}
}
private void SendMsg_Click(object sender, EventArgs e)
{
int m_length = mymessage.Text.Length;
byte[] data=new byte[m_length];
data = Encoding.UTF8.GetBytes(mymessage.Text);
int i = newclient.Send(data);
showMsg("我说:" + mymessage.Text + "\r\n");
//receiveMsg.AppendText("我说:"+mymessage.Text + "\r\n");
mymessage.Text = "";
//newclient.Shutdown(SocketShutdown.Both);
}
private void connect_Click(object sender, EventArgs e)
{
Connect();
}
}来自于:http://hi.baidu.com/wuyunju/item/006610520eb58e968c12eda0
最新文章
- MongoDB 存储引擎:WiredTiger和In-Memory
- 家族/亲戚(relation)
- .Net生成HTML的三种方法
- html不使用cache数据
- cvWaitKey 如果 cvNamedWindow就不会起作用
- 认识position=fixed
- SQL SERVER中查找某关键词位于哪些存储过程或函数
- 在类成员函数后面加const
- prim模板题
- 无向图求割点 UVA 315 	Network
- [转]Java虚拟机类加载机制浅谈
- 解决sqlserver2008 r2 登陆时报错:provider 命名管道提供程序, error40 错误2
- 用require.js封装原生js轮播图
- JAVA NIO学习三:NIO 的非阻塞式网络通信
- 可重复执行的SQL Script
- [Swift]LeetCode215. 数组中的第K个最大元素 | Kth Largest Element in an Array
- Softmax 回归 vs. k 个二元分类器
- qml(Qt Quick)做界面
- Spring MVC基础知识整理➣拦截器和自定义注解
- EF生成实体自动添加数据库字段注释
热门文章
- win7系统 连接打印机 提示 “正在检查 windows update 需要一段时间”
- 【RHEL7/CentOS7服务控制之systemctl命令】
- CCF模拟 I’m stuck!
- Junit4.x高级使用方法具体解释(一)
- Top 16 Java 应用类 - 这些功能再也不用自己写了
- Thinkphp5图片上传正常,音频和视频上传失败的原因及解决
- 62.C++文件操作list实现内存检索,实现两千万数据秒查
- 安装Domino分区服务器
- Kinect 开发 —— Kinect Interaction 交互控件
- Kinect 开发 —— 控制PPT播放