再次特别感谢张子阳老师的文章,读后深感益处。

废话不多说,先贴代码

这是服务器端代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Data.SqlClient;
namespace SeverConsole {
class Program {
const int bufferSize = 8192;//接受的最大字节数 static void Main(string[] args) {
Console.WriteLine("Sever is runing");
IPAddress ip = new IPAddress( new byte[]{127,0,0,1});
TcpListener tcpListener = new TcpListener(ip, 8500);//监听对象
tcpListener.Start(); while (true) {
try{
TcpClient remoteClient = tcpListener.AcceptTcpClient();//接受客户端的连接请求,会在此处等待。 不会继虚向下执行
Console.WriteLine(@"有客户端连入,{0}<--{1}", remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint); NetworkStream streamFromClient = remoteClient.GetStream();//获取连接到客户端的流
byte[] buffer = new byte[bufferSize];
int bytesRead = streamFromClient.Read(buffer, 0, bufferSize);//从客户端和服务器获取的流都是二进制形式的
Console.WriteLine("read {0} bytes from client", bytesRead);
string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received: {0}", msg); string magSend = msg.ToUpper();
buffer = Encoding.Unicode.GetBytes(magSend);
lock (streamFromClient) {//为了保证数据的完整性以及安全性 锁定数据流
streamFromClient.Write(buffer, 0, buffer.Length);
Console.WriteLine("send: {0}", msg.ToUpper());
} }catch(Exception ex){
Console.WriteLine(ex.Message);
} }
Console.WriteLine(@"please press 'Q' to exit");
//Console.ReadLine();
ConsoleKey key;
do {
key = Console.ReadKey().Key;
} while (key != ConsoleKey.Q);
}
}
}

这是客户端代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace clientConsole {
class Program {
const int bufferSize = 8192;
static void Main(string[] args) {
Console.WriteLine("Client is running!"); TcpClient client;
for (int i = 0; i < 4; i++) {
client = new TcpClient();
try {
client.Connect("127.0.0.1", 8500);
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
Console.WriteLine("connecting successful");
Console.WriteLine("{0}-->{1}", client.Client.LocalEndPoint, client.Client.RemoteEndPoint);
string msg = "let me to connect with you ";
NetworkStream clientToSever = client.GetStream();
byte[] buffer = Encoding.Unicode.GetBytes(msg);
clientToSever.Write(buffer, 0, buffer.Length);
int t = buffer.Length;
Console.WriteLine("Send: {0}", msg);
lock (clientToSever) {//
int bytesRead = clientToSever.Read(buffer, 0, t);
msg = Encoding.Unicode.GetString(buffer, 0, buffer.Length);
Console.WriteLine("Received: {0}", msg);
}
}
ConsoleKey key;
do {
key = Console.ReadKey().Key;
} while (key != ConsoleKey.Q); }
}
}

转载请说明出处

c#socket同步通信的更多相关文章

  1. (转载)所有分类 > 开发语言与工具 > 移动开发 > Android开发 Android中的Service:默默的奉献者 (1)

    前言 这段时间在看一些IPC相关的东西,这里面就不可避免的要涉及到service,进程线程这些知识点,而且在研究的过程中我惊觉自己对这些东西的记忆已经开始有些模糊了——这可要不得.于是我就干脆花了点心 ...

  2. Socket通讯实例-基本Socket

    转自:http://www.cnblogs.com/mahaisong/archive/2011/07/25/2116475.html (讲的很好,很细) 参考:http://blog.sina.co ...

  3. .net平台下C#socket通信(上)

    在开始介绍socket前先补充补充基础知识,在此基础上理解网络通信才会顺理成章,当然有基础的可以跳过去了.都是废话,进入正题. TCP/IP:Transmission Control Protocol ...

  4. C# Socket编程 同步以及异步通信

    套接字简介:套接字最早是Unix的,window是借鉴过来的.TCP/IP协议族提供三种套接字:流式.数据报式.原始套接字.其中原始套接字允许对底层协议直接访问,一般用于检验新协议或者新设备问题,很少 ...

  5. Socket 之 同步以及异步通信

    用netstat侦听下端口状态 同步通信: 预定义结构体,同步通信没有多线程异步委托回调,所以无需预定义结构体 客户端Client: class Program { static void Main( ...

  6. 【socket】Socket的三个功能类TCPClient、TCPListener 和 UDPClient

    Socket的三个功能类TCPClient.TCPListener 和 UDPClient (转) 应用程序可以通过 TCPClient.TCPListener 和 UDPClient 类使用传输控制 ...

  7. Socket异步通信学习一

    最近在做一个频谱管理项目,负责通信模块,自己也是小白,重头学起,直至今天通信基本框架已经完成,把自己在学习中的心得与大家分享一下,做一个socket系列的博文,顺便加固一下自己对socket通信的认识 ...

  8. Socket(TCP)客户端请求和服务端监听和链接基础(附例子)

    一:基础知识回顾 一: Socket 类 实现 Berkeley 套接字接口. Socket(AddressFamily, SocketType,ProtocolType) 使用指定的地址族.套接字类 ...

  9. C# Socket学习笔记二

    小记:昨天咱们已经了解了Socket的通信原理,可是点对点的一次通信并不是我们想要的,那么今天那我们就继续学习异步通信,简单来说就是服务器端和客户端可以进行多次 互发信息的通信而不用担心通道会关闭.在 ...

随机推荐

  1. (转)C# foreach 中获取索引index的方法

    在C# 开发中往往使用foreach 循环语句 来代替for循环语句.foreach 比 for 更加简洁高效.           foreach :                 foreach ...

  2. Java中HashMap等的实现要点浅析

    @南柯梦博客中的系列文章对Jdk中常用容器类ArrayList.LinkedList.HashMap.HashSet等的实现原理以代码注释的方式给予了说明(详见http://www.cnblogs.c ...

  3. mongoDB研究笔记:复制集故障转移机制

    上面的介绍的数据同步(http://www.cnblogs.com/guoyuanwei/p/3293668.html)相当于传统数据库中的备份策略,mongoDB在此基础还有自动故障转移的功能.在复 ...

  4. MongoDB索引的使用

    Table of Contents 1. 基本索引 2. 联合索引 3. 索引类型 4. 索引管理 1 基本索引 在数据库开发中索引是非常重要的,对于检索速度,执行效率有很大的影响.本 文主要描述了M ...

  5. 团队项目——站立会议DAY10

    第十次站立会议记录: 参会人员:张靖颜,钟灵毓秀,何玥,赵莹,王梓萱 项目进展: 1.张靖颜:进一步完善程序代码,提出扩展性的建议,增加程序的功能. 2.钟灵毓秀:修改已完成代码出现的bug,完善代码 ...

  6. 【读书笔记】WebApi 和 SPA(单页应用)--knockout的使用

    Web API从MVC4开始出现,可以服务于Asp.Net下的任何web应用,本文将介绍Web api在单页应用中的使用.什么是单页应用?Single-Page Application最常用的定义:一 ...

  7. 2015继续任性——不会Git命令,照样玩转Git

    最近事情比较多,一眨眼,已经半个月没有写博客了~不得不感慨光阴似箭啊!当然,2015年有很多让我们期待的事情,比如win10正式版..NET开源.VS2015等等.想想都让人兴奋啊~~ 为了迎接VS2 ...

  8. read links July-14

    1)   http://ruby-hacking-guide.github.io/intro.html It has one part to discuss “Technique to read so ...

  9. 在 Win10 命令行使用 Consolas + 微软雅黑

    这个过程挺神奇的,步骤参考了下面两篇文章,但是过程很曲折: 1. 使用Monaco和微软雅黑字体美化cmd和PowerShell 2. [zz]Windows的cmd.exe使用consolas加中文 ...

  10. Spring Trasnaction管理(2)- 事务AOP

    问题导读 spring AOP是在如何进行的 spring 用cglib和jdkProxy管理的事务有何区别 Spring AOP管理 Spring主要的两个核心功能IOC与AOP.IOC的代码解析可 ...