Socket,这玩意,当时不会的时候,抄别人的都用不好,简单的一句话形容就是“笨死了”;也是很多人写的太复杂,不容易理解造成的。最近在搞erlang和C的通讯,也想试试erlang是不是可以和C#简单通讯,就简单的做了些测试用例,比较简单,觉得新手也可以接受。

 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.Sockets;
using System.Net;
using System.Threading; namespace ChatClient
{
public partial class Form1 : Form
{
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.TextBox textBox1;
private System.ComponentModel.IContainer components = null; /// <summary>
/// 服务端侦听端口
/// </summary>
private const int _serverPort = ;
/// <summary>
/// 客户端侦听端口
/// </summary>
private const int _clientPort = ;
/// <summary>
/// 缓存大小
/// </summary>
private const int _bufferSize = ;
/// <summary>
/// 服务器IP
/// </summary>
private const string ServerIP = "172.17.47.199"; //手动修改为指定服务器ip private Thread thread; private void Form1_Load(object sender, EventArgs e)
{
thread = new Thread(new ThreadStart(delegate { Listenning(); }));
thread.Start();
} void textBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
string msg;
if ((msg = textBox1.Text.Trim()).Length > )
{
SendMessage(msg);
}
textBox1.Clear();
}
} void SendMessage(string msg)
{
try
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ServerIP), _serverPort);
socket.Connect(endPoint);
byte[] buffer = System.Text.ASCIIEncoding.UTF8.GetBytes(msg);
socket.Send(buffer);
socket.Close();
}
catch
{ }
} void Listenning()
{
TcpListener listener = new TcpListener(_clientPort);
listener.Start();
while (true)
{
Socket socket = listener.AcceptSocket();
byte[] buffer = new byte[_bufferSize];
socket.Receive(buffer);
int lastNullIndex = _bufferSize - ;
while (true)
{
if (buffer[lastNullIndex] != '\0')
break;
lastNullIndex--;
}
string msg = Encoding.UTF8.GetString(buffer, , lastNullIndex + );
WriteLine(msg);
socket.Close();
}
} void WriteLine(string msg)
{
this.Invoke(new MethodInvoker(delegate
{
this.richTextBox1.AppendText(msg + Environment.NewLine);
}));
} public Form1()
{
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(, );
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(, );
this.richTextBox1.TabIndex = ;
this.richTextBox1.Text = "";
this.richTextBox1.KeyUp += new System.Windows.Forms.KeyEventHandler(this.textBox_KeyUp);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(, );
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(, );
this.textBox1.TabIndex = ;
this.textBox1.KeyUp += new System.Windows.Forms.KeyEventHandler(this.textBox_KeyUp);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(, );
this.Controls.Add(this.richTextBox1);
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
} protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
}
}

Client端

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections; namespace ChatService
{
public partial class Service1 : ServiceBase
{
/// <summary>
/// 服务端侦听端口
/// </summary>
private const int _serverPort = ;
/// <summary>
/// 客户端侦听端口
/// </summary>
private const int _clientPort = ;
/// <summary>
/// 缓存大小
/// </summary>
private const int _bufferSize = ;
/// <summary>
/// 服务器IP
/// </summary>
private const string ServerIP = "172.17.47.199"; //手动修改为指定服务器ip
/// <summary>
/// 客户端IP
/// </summary>
//private Hashtable ServerIPs = new Hashtable(); //存放ip + port
private List<string> ServerIPs = new List<string>(); public Service1()
{
//InitializeComponent(); //从控制台改为服务,需要注释下面的一行,打开本行
Listenning();
} void SendMessage(string from, string msg)
{ for (int i = ServerIPs.Count - ; i >= ; i--)
{
try
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ServerIPs[i]), _clientPort);
socket.Connect(endPoint);
byte[] buffer = System.Text.ASCIIEncoding.UTF8.GetBytes((from + " say: " + msg).Trim());
socket.Send(buffer);
socket.Close();
}
catch
{
ServerIPs.RemoveAt(i);
}
}
} void Listenning()
{ TcpListener listener = new TcpListener(_serverPort);
listener.Start();
while (true)
{
Socket socket = listener.AcceptSocket();
var s = socket.RemoteEndPoint.ToString();
var ipstr = s.Substring(, s.IndexOf(":")); if (!ServerIPs.Contains(ipstr))
{
ServerIPs.Add(ipstr);
} byte[] buffer = new byte[_bufferSize];
socket.Receive(buffer);
int lastNullIndex = _bufferSize - ; while (true)
{
if (buffer[lastNullIndex] != '\0')
break;
lastNullIndex--;
}
string msg = Encoding.UTF8.GetString(buffer, , lastNullIndex + );
SendMessage(ipstr,msg);
Console.WriteLine(msg);//服务模式下关闭
}
} protected override void OnStart(string[] args)
{
Listenning();
} protected override void OnStop()
{ }
}
}

Server端

逻辑视图(比较简单):

1.左上角的是一个远程客户端,右上角是本地客户端,右下角是本地服务端(暂时改为控制台程序)

2.这段程序只给不懂得如何用socket玩玩

3.这里面剔除了数据加密、异步获取等繁杂的过程,想要学习可以参照:http://yunpan.cn/cKT2ZHdKRMILz  访问密码 b610

[C#] Socket 通讯,一个简单的聊天窗口小程序的更多相关文章

  1. 使用vue+koa实现一个简单的图书小程序(1)

    这个系列的博客用来记录我开发时候遇到的问题以及学习到的知识 边做边学: 前后端分离,高内聚低耦合小程序端使用了mpvue 内部使用了vuejs的语法 来做整个小程序的渲染层 后端使用的是koa2搭建一 ...

  2. 一个简单的servlet小程序

    servlet是不能单独运行的,他是运行在web服务器或应用服务器上的java程序,或者可以说是在servlet容器上运行的,我们经常使用到的tomcat就是一个servlet容器. 他是处理HTTP ...

  3. java实现一个简单的爬虫小程序

    前言 前些天无意间在百度搜索了一下以前写过的博客 我啥时候在这么多不知名的网站上发表博客了???点进去一看, 内容一模一样,作者却不是我... 然后又去搜了其他篇博客,果然,基本上每篇都在别的网站上有 ...

  4. 一个简单的Android小实例

    原文:一个简单的Android小实例 一.配置环境 1.下载intellij idea15 2.安装Android SDK,通过Android SDK管理器安装或卸载Android平台   3.安装J ...

  5. 一个简单的Maven小案例

    Maven是一个很好的软件项目管理工具,有了Maven我们不用再费劲的去官网上下载Jar包. Maven的官网地址:http://maven.apache.org/download.cgi 要建立一个 ...

  6. IOS开发之小实例--使用UIImagePickerController创建一个简单的相机应用程序

    前言:本篇博文是本人阅读国外的IOS Programming Tutorial的一篇入门文章的学习过程总结,难度不大,因为是入门.主要是入门UIImagePickerController这个控制器,那 ...

  7. Linux下简单C语言小程序的反汇编分析

    韩洋原创作品转载请注明出处<Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000 写在开始,本文为因为参加MOO ...

  8. 【云开发】10分钟零基础学会做一个快递查询微信小程序,快速掌握微信小程序开发技能(轮播图、API请求)

    大家好,我叫小秃僧 这次分享的是10分钟零基础学会做一个快递查询微信小程序,快速掌握开发微信小程序技能. 这篇文章偏基础,特别适合还没有开发过微信小程序的童鞋,一些概念和逻辑我会讲细一点,尽可能用图说 ...

  9. 一个简单的P2P传输程序

    写了一个简单的P2P传输程序,在P2P的圈子中传输文件,不过为了简便,这个程序没有真正的传输文件,只是简单的判断一下文件的位置在哪里.这个程序可以处理当有一个peer闪退的情况,在这种情况下,剩下的p ...

随机推荐

  1. 1、Spring In Action 4th笔记(1)

    Spring In Action 4th笔记(1) 2016-12-28 1.Spring是一个框架,致力于减轻JEE的开发,它有4个特点: 1.1 基于POJO(Plain Ordinary Jav ...

  2. 【校验】TCP和UDP的校验和

    一开始,私以为校验和只是简单的求和得到的结果,后来在TCP和UDP里面看到使用的校验和方式有点奇怪--二进制反码(循环进位)求和. 人类的认知过程必将从简单到复杂,看下这个二进制反码循环求和是啥子意思 ...

  3. 【AspNet Core】Nuget代理网站

    因为访问Nuget太慢,在Dotnet Core RC2发布前,我就基于Asp.Net做了一个Nuget代理网站 这是网站地址:http://nuget.lzzy.net/ Nuget源:http:/ ...

  4. Java 实现HTML富文本导出至word完美解决方案

    一. 问题的提出 最近用java开发一个科技项目信息管理系统,里面有一个根据项目申请书的模板填写项目申报信息的功能,有一个科技项目申请书word导出功能. 已有的实现方式:采用标准的jsp模板输出实现 ...

  5. 移动端常用的meta

    1. 禁止缩放:<meta name="viewport" content="width=device-width, initial-scale=1.0, maxi ...

  6. php 用 http post方法传输数据

    private function http_post($url,$post,$timeout){ $curl = curl_init(); curl_setopt($curl, CURLOPT_URL ...

  7. GiuHub 使用

    一 Mac 能不能连接安卓手机 1 USB数据线  设置 > 通用 > 开发人员选项 > USB调试 > 选择"相机PTP模式"  连接后,手机中的照片和视 ...

  8. 不需要sql进行计算数据的平均值、最大值、最小值、和

    介绍下SqlServer.前端js.后台C#三个阶段对均值.最大值.最小值.和计算int[] jisuan = {0, 1, 3, 5, 7,8 }; List<int> jisuan2 ...

  9. 通过修改i8042prt端口驱动中类驱动Kbdclass的回调函数地址,达到过滤键盘操作的例子

    同样也是寒江独钓的例子,但只给了思路,现贴出实现代码 原理是通过改变端口驱动中本该调用类驱动回调函数的地方下手 //替换分发函数 来实现过滤 #include <wdm.h> #inclu ...

  10. SharePoint 2010 Survey的Export to Spreadsheet功能怎么不见了?

    背景信息: 最近用户报了一个问题,说他创建的Survey里将结果导出成Excel文件(Export to spreadsheet)的按钮不见了. 原因排查: 正常情况下,这个功能只存在于SharePo ...