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. iOS automaticallyAdjustsScrollViewInsets

    self.automaticallyAdjustsScrollViewInsets = NO; //在当前VC内修改这个属性就可以解决这个问题了. 当前以TableView为主View的ViewCon ...

  2. bzoj4491奇技淫巧线段树

    20行的归并+10行的线段树(现在线段树真是越写越短了)+10行主程序(连主程序都缩过行)  = =丧心病狂 struct里连开10个,用大括号直接初始化真是爽翻了 #include <cstd ...

  3. css 大话盒子模型

    什么是盒子模型? CSS中, Box Model叫盒子模型(或框模型),Box Model规定了元素框处理元素内容(element content).内边距(padding).边框(border) 和 ...

  4. 2015-12-23-( dispaly:table的用法)

    dispaly属性的table和table-cell属性值不怎么常用,主要是浏览器的兼容性不好,大多数都是为了兼容IE6.IE7,此属性IE8以上,谷歌,火狐,oprea等浏览器都支持.  此disp ...

  5. 【翻译】Express web应用开发 第一章

    本章节是一个对初学者友好的Express介绍.你将学习到Express的基础知识.核心概念和实现一个Express应用的组成部分.现阶段我们不需要做太多的编码,本章节会让你熟悉和习惯Express,为 ...

  6. TPC-H生成.tbl文件导入postgresql数据库的坑

    数据库project好好的不用主流的MySQL和Microsoft server而要求用听都没听过的postgresql (当然,可能你三个都没听过) 这里的坑主要是把生成的那八张.tbl的表导入pg ...

  7. #iOS问题记录#关于NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9801)

    响应Apple的号召,将APP里的HTTP请求全部升级为HTTPS,一切配置OK,正常的请求也没问题: 但,当使用SDwebImg缓存图片时,遇到了标题写的问题: 根据资料得: 这个问题的出现是因为i ...

  8. VS调试程序时一闪而过的问题-解决方法(网上搜集)

    在VS2012里的控制台应用程序在运行时,结果画面一闪而过,不管是用F5 还是用Ctrl + F5都是一样,导致无法看到结果. 网上有不少的办法,说是都是在程序最后加一个要程序暂停的语句或从控制台上获 ...

  9. Java实现文件在某个目录的检索

    package com.filetest; import java.io.File; import java.util.Date; import java.util.Scanner; public c ...

  10. ecshop二次开发 商品分类描述编辑框