整理一份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 学习实例的更多相关文章

  1. 网络协议栈学习(一)socket通信实例

    网络协议栈学习(一)socket通信实例 该实例摘自<linux网络编程>(宋敬彬,孙海滨等著). 例子分为服务器端和客户端,客户端连接服务器后从标准输入读取输入的字符串,发送给服务器:服 ...

  2. Linux下简单的socket通信实例

    Linux下简单的socket通信实例 If you spend too much time thinking about a thing, you’ll never get it done. —Br ...

  3. 你也可以写个服务器 - C# Socket学习2

    前言 这里说的服务器是Web服务器,是类似IIS.Tomcat之类的,用来响应浏览器请求的服务. Socket模拟浏览器的Url Get请求 首先浏览器的请求是HTTP协议.我们上一篇说过,HTTP是 ...

  4. Flex通信-与Java实现Socket通信实例

    Flex通信-与Java实现Socket通信实例  转自:http://blessht.iteye.com/blog/1136888 博客分类: Flex 环境准备 [服务器端] JDK1.6,“ja ...

  5. Ant学习实例

    ant   目录(?)[+] Ant学习实例 安装Ant 基础元素 project元素 target元素 property元素 完整示例   Ant学习实例 1.安装Ant 先从http://ant. ...

  6. Socket 学习(三).4 UDP 穿透 客户端与客户端连接

    效果图: 使用方法:  先 修改WinClient\bin\Debug  下面的 ip.ini,写上 服务器 IP地址. 客户端 与 客户端 通讯 之前 ,点击发送打洞消息 按钮,然后过一会再发送消息 ...

  7. 在windows下用C语言写socket通讯实例

    原文:在windows下用C语言写socket通讯实例 From:Microsoft Dev Center #undef UNICODE #define WIN32_LEAN_AND_MEAN #in ...

  8. Socket学习总结系列(二) -- CocoaAsyncSocket

    这是系列的第二篇 这是这个系列文章的第二篇,要是没有看第一篇的还是建议看看第一篇,以为这个是接着第一篇梳理的 先大概的总结一下在上篇的文章中说的些内容: 1. 整理了一下做IM我们有那些途径,以及我们 ...

  9. linux下socket编程实例

    linux下socket编程实例一.基本socket函数Linux系统是通过提供套接字(socket)来进行网络编程的.网络的socket数据传输是一种特殊的I/O,socket也是一种文件描述符.s ...

随机推荐

  1. spark MySQL jar 包

    /** * Created by songcl on 2016/6/24. */ import java.sql.DriverManager //val sqlContext = new org.ap ...

  2. bit操作 转

    http://www.catonmat.net/blog/low-level-bit-hacks-you-absolutely-must-know/ Bit Hack #6. Turn off the ...

  3. android SDK Manager 上载失败

    android SDK Manager 下载失败如题,利用android SDK Manager 无法下载各个版本的SDK,是最近无法连接上谷歌的服务器吗?我用了网上说的在C:\WINDOWS\sys ...

  4. Ubuntu 中搭建 LAMP 及 php 开发工具

    所谓 LAMP,指的是:Linux+Apache+Mysql+Php 仅以此文做一个备忘录 Step1. 安装 Apache 1. 在 terminal 中输入一下命令并执行: sudo apt-ge ...

  5. 安卓开发笔记——自定义HorizontalScrollView控件(实现QQ5.0侧滑效果)

    对于滑动菜单栏SlidingMenu,大家应该都不陌生,在市场上的一些APP应用里经常可以见到,比如人人网,FaceBook等. 前段时间QQ5.0版本出来后也采用了这种设计风格:(下面是效果图) 之 ...

  6. Android样式的开发:Style篇

    前面铺垫了那么多,终于要讲到本系列的终篇,整合所有资源,定义成统一的样式.哪些该定义成统一的样式呢?举几个例子吧: 每个页面标题栏的标题基本会有一样的字体大小.颜色.对齐方式.内间距.外间距等,这就可 ...

  7. 尝试在virtualbox fedora21 下安装additions和mount share folder

    安装这个additions的过程,基本上可以参照 http://gamblisfx.com/how-to-install-virtualbox-guest-additions-on-fedora-21 ...

  8. Apache 配置多端口网站

    跳过安装步骤. 1. apache安装目录/conf/httpd.conf,如果你是采用wamp集成环境,那么在 wamp/bin/apache下. 2. 在httpd.conf中,找到 #LoadM ...

  9. google翻译,翻译当前的网页

    网页翻译为德语(Translate Page To German) <a href="javascript: void(window.open('http://translate.go ...

  10. mysql中连接失败2003错误解决办法

    在使用mysql数据库,新建连接时,会报2003-Can't connect to server on 'localhost'(10038)错误,原因主要是MYSQL服务没有启动起来,但是进入:计算机 ...