Socket 学习实例
整理一份Socket代码,整理前辈的代码
http://www.cnblogs.com/yellowapplemylove/archive/2011/04/19/2021586.html
直接贴代码
一、客户端
/// <summary>
/// Client客户端
/// </summary>
public partial class ClientForm : Form
{
private IPAddress serverIp ;
private IPEndPoint serverFullAddr;
private Socket sock;
public ClientForm()
{
InitializeComponent();
this.Load += (e, v) =>
{
txtIP.Text = "127.0.0.1";
txtPort.Text = "";
};
}
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
serverIp = IPAddress.Parse(txtIP.Text.Trim());
serverFullAddr = new IPEndPoint(serverIp, int.Parse(txtPort.Text.Trim()));
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(serverFullAddr);//建立与远程主机的连接
//启动新线程用于接收数据
Thread t = new Thread(new ThreadStart(ReceiveMsg));
t.Name = "接收消息";
//一个线程或者是后台线程或者是前台线程。后台线程与前台线程类似,区别是后台线程不会防止进程终止。
//一旦属于某一进程的所有前台线程都终止,公共语言运行库就会通过对任何仍然处于活动状态的后台线程调用 abort 来结束该进程。
t.IsBackground = true;
t.Start();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReceiveMsg()
{
try
{
while (true)
{
byte[] byterec = new byte[];
this.sock.Receive(byterec);
string strrec = System.Text.Encoding.UTF8.GetString(byterec);
if (this.txtReceive.InvokeRequired)
{
this.txtReceive.Invoke(new EventHandler(ChangerText), new object[] { strrec, EventArgs.Empty });
}
}
}
catch (Exception ex)
{
MessageBox.Show("接收服务器消息发生错误" + ex.Message);
}
}
private void ChangerText(object obj, EventArgs e)
{
string s = Convert.ToString(obj);
this.txtReceive.AppendText(s + Environment.NewLine);
}
private void btnSend_Click(object sender, EventArgs e)
{
byte[] byteSend =System.Text.Encoding.UTF8.GetBytes(this.txtSend.Text.ToCharArray());
try
{
sock.Send(byteSend);
}
catch
{
MessageBox.Show("向服务器发送数据错误");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
try
{
this.sock.Shutdown(SocketShutdown.Receive);
this.sock.Close();
Application.Exit();
}
catch
{
MessageBox.Show("关闭连接发生错误");
}
}
}
二、服务器端
public partial class ServerForm : Form
{
private IPAddress serverIp ;//IP地址
private IPEndPoint serverFullAddr;//完整终端地址
private Socket sock;
private System.Timers.Timer timer;
private ArrayList allStocksList;//当建立了多个连接时用于保存连接
public ServerForm()
{
InitializeComponent();
this.Load += (e, v) =>
{
txtIP.Text = "127.0.0.1";
txtPort.Text = "";
};
}
private void btstart_click(object sender, EventArgs e)
{
serverIp = IPAddress.Parse(txtIP.Text.Trim());
serverFullAddr = new IPEndPoint(serverIp, int.Parse(txtPort.Text.Trim()));
//构造socket对象,套接字类型为“流套接字”,指定五元组中的协议元
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
//指定五元组中的本地二元,即本地主机地址和端口号
sock.Bind(serverFullAddr);
//监听是否有连接传入,指定挂起的连接队列的最大值为20
sock.Listen();
allStocksList = new ArrayList();
//构造定时器,时间间隙为1秒,即每隔一秒执行一次accept()方法,以获取连接请求队列中//第一个挂起的连接请求
timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
timer.Enabled = false;
//执行accept(),当挂起队列为空时将阻塞本线程,同时由于上一语句,定时器将停止,直//至有连接传入
Socket acceptSTock = sock.Accept();
//将accept()产生的socket对象存入arraylist
allStocksList.Add(acceptSTock);
// 构造threading.timer对象,这将导致程序另启线程。线程将执行回调函数,该委托限制//函数参数须为object型。
//threading.timer构造器的第二个参数即传入回调函数的参数;第//三个参数指定调用回调函数之前的延时,取0则立即启动;
//最后一个参数指定调用回调函数//的时间间隔,取0则只执行一次。
System.Threading.Timer ti = new System.Threading.Timer(new TimerCallback(receivemsg), acceptSTock, , );
timer.Enabled = true;
} private void receivemsg(object obj)
{
Socket acceptStock = (Socket)obj;
try
{
while (true)
{
byte[] byteArray = new byte[];
acceptStock.Receive(byteArray);//接收数据
//将字节数组转成字符串
string strrec = System.Text.Encoding.UTF8.GetString(byteArray);
if (this.txtReceive.InvokeRequired)
{
this.txtReceive.Invoke(new EventHandler(this.ChangerText), new object[] { strrec, EventArgs.Empty });
}
}
}
catch (Exception ex)
{
acceptStock.Close();
MessageBox.Show("接收客户端消息错误" + ex.Message);
}
}
private void ChangerText(object obj, EventArgs e)
{
string s = Convert.ToString(obj);
this.txtReceive.AppendText(s + Environment.NewLine);
}
private void btnSend_Click(object sender, EventArgs e)
{
Socket sc = null;
byte[] byteSend =System.Text.Encoding.UTF8.GetBytes(this.tbsend.Text.ToCharArray());
try
{
//向所有的客户端发送数据
for (int i = ; i < allStocksList.Count; i++)
{
sc = allStocksList[i] as Socket;
sc.Send(byteSend);
}
}
catch (Exception ex)
{
if (sc != null)
{
sc.Close();
} MessageBox.Show("向客户端发送信息错误" + ex.Message);
}
} private void btnClose_Click(object sender, EventArgs e)
{
try
{
Application.Exit();
}
catch (Exception ex)
{
MessageBox.Show("关闭连接发生错误" + ex.Message);
}
}
}
Socket 学习实例的更多相关文章
- 网络协议栈学习(一)socket通信实例
网络协议栈学习(一)socket通信实例 该实例摘自<linux网络编程>(宋敬彬,孙海滨等著). 例子分为服务器端和客户端,客户端连接服务器后从标准输入读取输入的字符串,发送给服务器:服 ...
- Linux下简单的socket通信实例
Linux下简单的socket通信实例 If you spend too much time thinking about a thing, you’ll never get it done. —Br ...
- 你也可以写个服务器 - C# Socket学习2
前言 这里说的服务器是Web服务器,是类似IIS.Tomcat之类的,用来响应浏览器请求的服务. Socket模拟浏览器的Url Get请求 首先浏览器的请求是HTTP协议.我们上一篇说过,HTTP是 ...
- Flex通信-与Java实现Socket通信实例
Flex通信-与Java实现Socket通信实例 转自:http://blessht.iteye.com/blog/1136888 博客分类: Flex 环境准备 [服务器端] JDK1.6,“ja ...
- Ant学习实例
ant 目录(?)[+] Ant学习实例 安装Ant 基础元素 project元素 target元素 property元素 完整示例 Ant学习实例 1.安装Ant 先从http://ant. ...
- Socket 学习(三).4 UDP 穿透 客户端与客户端连接
效果图: 使用方法: 先 修改WinClient\bin\Debug 下面的 ip.ini,写上 服务器 IP地址. 客户端 与 客户端 通讯 之前 ,点击发送打洞消息 按钮,然后过一会再发送消息 ...
- 在windows下用C语言写socket通讯实例
原文:在windows下用C语言写socket通讯实例 From:Microsoft Dev Center #undef UNICODE #define WIN32_LEAN_AND_MEAN #in ...
- Socket学习总结系列(二) -- CocoaAsyncSocket
这是系列的第二篇 这是这个系列文章的第二篇,要是没有看第一篇的还是建议看看第一篇,以为这个是接着第一篇梳理的 先大概的总结一下在上篇的文章中说的些内容: 1. 整理了一下做IM我们有那些途径,以及我们 ...
- linux下socket编程实例
linux下socket编程实例一.基本socket函数Linux系统是通过提供套接字(socket)来进行网络编程的.网络的socket数据传输是一种特殊的I/O,socket也是一种文件描述符.s ...
随机推荐
- 自己做的加速app测试流程的小工具,目前打算开放使用,想注册的朋友抓紧了,嘻嘻
为了加速小团队app的测试流程做了这个东西,www.xunce.net 主要特性: web: 一键上传app,方便随时下载 备注测试要点 添加附件,如checklist等文档 自动识别app版本,名 ...
- mysql查看和修改最大数量
通常,mysql的最大连接数默认是100, 最大可以达到16384.1.查看最大连接数:show variables like '%max_connections%';2.修改最大连接数方法一:修改配 ...
- Some User Can Not Execute "Ship Confirm"(Doc ID 473312.1)
APPLIES TO: Oracle Shipping Execution - Version 11.5.10.2 and later Information in this document app ...
- 在MACOS上实现交叉编译
在嵌入式开发过程中,设备的存储空间和运算能力通常会比较低,这时候,比如要编译一个linux的内核,嵌入式设备就不能胜任了,所以,实现交叉编译还是很必要的.通过交叉编译,我们就能够在我们的pc上编译出能 ...
- ASP.NET MVC 4 Web编程
http://spu.jd.com/11309606.html 第1章 入门第2章 控制器第3章 视图第4章 模型第5章 表单和HTML辅助方法第6章 数据注解和验证第7章 成员资格.授权和安全性第8 ...
- 【翻译】VSM 和触发器
原文:The VisualStateManager and Triggers Author:Carole Snyder Silverlight 推出了可视化状态管理器( Visual State Ma ...
- DDD:当视图模型、领域模型和数据模型都采用了同样的类型的时候,我们该如何处理?
如果采用这种模式,模型会在不同的逻辑层之间传递,以向内传递为例,模型的状态变化是由外向内的不同逻辑层负责修改的,因为这种模式下模型的封装性是很差的,架构和框架要做到:清晰的表达每个逻辑层该如何使用和修 ...
- jackson反序列化时忽略不需要的字段
有时候,如果数据库表中增加一个字段,但返回的JSON字符串中含有我们并不需要的字段,那么当对应的实体类中不含有该字段时,会抛出一个异常,告诉你有些字段没有在实体类中找到.解决办法很简单,在声明Obje ...
- 使用ELK(Elasticsearch + Logstash + Kibana) 搭建日志集中分析平台实践--转载
原文地址:https://wsgzao.github.io/post/elk/ 另外可以参考:https://www.digitalocean.com/community/tutorials/how- ...
- How can I learn to program?
黑客与画家:硅谷创业之父paul graham关于回答‘How can I learn to program’ How can I learn to program? Find a friend wh ...