1.0 版本

1.1 服务器端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks; namespace Server_1._0
{
class Program
{
static void Main(string[] args)
{
//01 创建对象 关键字new
Socket stk = new Socket(AddressFamily.InterNetwork,//设置IP地址的类型 为ip4
SocketType.Stream, //设置传输方式 为流式传输
ProtocolType.Tcp//设置传输协议 为Tcp
);
//02 绑定对象 关键字bind()
stk.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), ));
//03 监听对象 关键字Listen()
stk.Listen();
Console.WriteLine("服务器启动成功!");
//04 接受客户端 关键字Accept() {证明Accept会阻塞线程}
Socket client = stk.Accept();
Console.WriteLine("服务器接受到客户端请求!");
//05 接受报文 关键字receive
//05-01 通过字节流传递 定义一个字节数组 {证明Receive也会阻塞线程}
byte[] bys = new byte[];
int len = client.Receive(bys);
Console.WriteLine("服务器接收到报文");
//06 显示接收到的字节数组
string str = Encoding.UTF8.GetString(bys, , len);
Console.WriteLine(str);
//07 发送消息 关键字 send
string mes = "已成功接收到你发的消息:<" + str + ">";
client.Send(Encoding.UTF8.GetBytes(mes));
Console.ReadKey(); }
}
}

Server

1.2 客户端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks; namespace Client_1._0
{
class Program
{
static void Main(string[] args)
{
//01 创建socket 关键字new
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//02 创建连接 关键字connect
client.Connect(IPAddress.Parse("127.0.0.1"),);
Console.WriteLine("与服务器创建连接");
//03 发送消息 关键字Send
//03-01 定义字节数组
byte[] bys = new byte[];
if (Console.ReadLine() == "")
{
bys = Encoding.UTF8.GetBytes("逍遥小天狼");
client.Send(bys);
Console.WriteLine("向服务器发送消息!");
}
//04 接受消息
//int len = 0;
//while ((len = client.Receive(bys))>0)
//{
// string s2 = Encoding.UTF8.GetString(bys, 0, len);
// Console.Write(s2); //}
byte [] by = new byte[];
int len = client.Receive(by);
Console.WriteLine(Encoding.UTF8.GetString(by,,len)); Console.ReadKey();
}
}
}

Client

2.0 版本

2.1 服务器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace Server_1._0
{
class Program
{
static void Main(string[] args)
{
//01 创建对象 关键字new
Socket stk = new Socket(AddressFamily.InterNetwork,//设置IP地址的类型 为ip4
SocketType.Stream, //设置传输方式 为流式传输
ProtocolType.Tcp//设置传输协议 为Tcp
);
//02 绑定对象 关键字bind()
stk.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), ));
//03 监听对象 关键字Listen()
stk.Listen();
Console.WriteLine("服务器启动成功!");
#region 旧的代码
////04 接受客户端 关键字Accept() {证明Accept会阻塞线程}
//Socket client = stk.Accept();
//Console.WriteLine("服务器接受到客户端请求!");
////05 接受报文 关键字receive
////05-01 通过字节流传递 定义一个字节数组 {证明Receive也会阻塞线程}
//byte[] bys = new byte[1024];
//int len = client.Receive(bys);
//Console.WriteLine("服务器接收到报文");
////06 显示接收到的字节数组
//string str = Encoding.UTF8.GetString(bys, 0, len);
//Console.WriteLine(str);
#endregion #region 新的代码 -- 通过 线程解决阻塞问题
Thread thClient = new Thread((s) =>
{
while (true)
{
//04 接受客户端 关键字Accept
Socket server = s as Socket;
Socket client = server.Accept();
//04-01 输出具体连接的客户端
Console.WriteLine("---客户端" + client.RemoteEndPoint + "连接");
//05 获取报文
Thread thReceive = new Thread((c) =>
{
Socket cClient = c as Socket;
byte[] bs = new byte[];
int len;
while ((len = cClient.Receive(bs)) > )
{
Console.WriteLine(Encoding.UTF8.GetString(bs, , len));
}
});
thReceive.IsBackground = true;
thReceive.Start(client);
}
});
thClient.IsBackground = true;
thClient.Start(stk);
#endregion
//07 发送消息 关键字 send
//string mes = "已成功接收到你发的消息:<" + str + ">";
// client.Send(Encoding.UTF8.GetBytes(mes));
Console.ReadKey(); }
}
}

2.2 客户端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks; namespace Client_1._0
{
class Program
{
static void Main(string[] args)
{
//01 创建socket 关键字new
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//02 创建连接 关键字connect
client.Connect(IPAddress.Parse("127.0.0.1"),);
Console.WriteLine("与服务器创建连接");
//03 发送消息 关键字Send
//03-01 定义字节数组
byte[] bys = new byte[];
string str = string.Empty;
while ((str = Console.ReadLine()) != "")
{
bys = Encoding.UTF8.GetBytes(str);
client.Send(bys);
Console.WriteLine("向服务器发送消息!");
}
//04 接受消息
#region 04-01 接受消息01
//int len = 0;
//while ((len = client.Receive(bys))>0)
//{
// string s2 = Encoding.UTF8.GetString(bys, 0, len);
// Console.Write(s2); //}
#endregion
#region 04-02 接受消息2
//byte[] by = new byte[1024];
//int len = client.Receive(by);
//Console.WriteLine(Encoding.UTF8.GetString(by, 0, len)); #endregion Console.ReadKey();
}
}
}

3.0 版本  Winfrom程序

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms; namespace Server_Form
{
public partial class frmServer : Form
{
public frmServer()
{
InitializeComponent();
}
#region 00 客户端字典
private Dictionary<string,Socket> dicClient = new Dictionary<string, Socket>( );
#endregion
#region 01 启动服务器
private void button1_Click(object sender, EventArgs e)
{
//01 创建连接对象
Socket serverSCK = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//02 绑定
serverSCK.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"),));
//03 监听
serverSCK.Listen();
txtMsg.Text = "服务器启动成功!\r\n";
//04 接受客户端的线程
Thread thClient = new Thread((server) =>
{
Socket serverSocket = server as Socket;
//05 接受客户端
while (true)
{
Socket clientSCK = serverSocket.Accept(); txtMsg.Invoke(new Action<string> ( (s) =>
{
//01 提示连接成功
txtMsg.Text += s + "连接成功!\r\n";
//02 将客户信息显示到列表中
clientList.Invoke(new Action<string>((ip) =>
{
clientList.Items.Add(ip);
}),s);
//03 将客户端放入到字典中
dicClient.Add(s, clientSCK);
}),clientSCK.RemoteEndPoint.ToString());
//06 接受客户端传来的报文的线程
Thread thReceive = new Thread((clientSocket) =>
{
Socket concentSocket = clientSocket as Socket;
byte[] bys = new byte[];
int len = ;
while ((len = concentSocket.Receive(bys))>)
{
//处理请求信息
txtMsg.Invoke(new Action<string>((s) =>
{
txtMsg.Text += s + "\r\n";
}),concentSocket.RemoteEndPoint.ToString()+":"+Encoding.UTF8.GetString(bys,,len));
}
});
thReceive.IsBackground = true;
thReceive.Start(clientSCK);
}
});
thClient.IsBackground = true;
thClient.Start(serverSCK);
}
#endregion #region 06 发送消息
private void btnSend_Click(object sender, EventArgs e)
{
//01 获得连接的客户端的字符串
string clientKey = clientList.SelectedItem.ToString();
//02 根据字符串获得客户端
Socket clientSCK = dicClient[clientKey];
//03 发送消息
clientSCK.Send(Encoding.UTF8.GetBytes(txtSendMsg.Text));
}
#endregion }
}

Server

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms; namespace Client_Form
{
public partial class FtmClient : Form
{
public FtmClient()
{
InitializeComponent();
}
#region 00 声明全局变量 private Socket client;
#endregion
#region 01 连接服务器
private void btnConnect_Click(object sender, EventArgs e)
{
//01 创建连接对象
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//02 连接
client.Connect(IPAddress.Parse(txtIP.Text),int.Parse(txtPort.Text));
txtSendMsg.Text += "与服务器连接成功!\r\n";
//03 接受响应消息
Thread thReceive = new Thread((clientSck) =>
{
Socket clientRecive = clientSck as Socket;
byte[] bys = new byte[];
int len = ;
while ((len = clientRecive.Receive(bys))>)
{
txtRecMsg.Invoke(new Action<string>(s =>
{
txtRecMsg.Text += s + "\r\n";
}),Encoding.UTF8.GetString(bys,,len));
} });
thReceive.IsBackground = true;
thReceive.Start(client);
}
#endregion #region 02 关闭窗体时清空socket 否则连接会出错
private void FtmClient_FormClosed(object sender, FormClosedEventArgs e)
{
client.Shutdown(SocketShutdown.Both);
client.Close();
client.Dispose();
}
#endregion #region 03 发送消息
private void btnSend_Click(object sender, EventArgs e)
{
//01 判断是否为空
if (client!= null)
{
client.Send(Encoding.UTF8.GetBytes(txtSendMsg.Text));
}
}
#endregion
}
}

Client

步步为营-66-Socket通信的更多相关文章

  1. AgileEAS.NET SOA 中间件平台.Net Socket通信框架-介绍

    一.前言 AgileEAS.NET SOA 中间件平台是一款基于基于敏捷并行开发思想和Microsoft .Net构件(组件)开发技术而构建的一个快速开发应用平台.用于帮助中小型软件企业建立一条适合市 ...

  2. iOS开发之Socket通信实战--Request请求数据包编码模块

    实际上在iOS很多应用开发中,大部分用的网络通信都是http/https协议,除非有特殊的需求会用到Socket网络协议进行网络数 据传输,这时候在iOS客户端就需要很好的第三方CocoaAsyncS ...

  3. AgileEAS.NET SOA 中间件平台.Net Socket通信框架-简单例子-实现简单的服务端客户端消息应答

    一.AgileEAS.NET SOA中间件Socket/Tcp框架介绍 在文章AgileEAS.NET SOA 中间件平台Socket/Tcp通信框架介绍一文之中我们对AgileEAS.NET SOA ...

  4. C# socket通信

    最近在研究socket,今天看到很好的一篇关于socket通信的文章,故收藏了,慢慢琢磨. 我们在讲解Socket编程前,先看几个和Socket编程紧密相关的概念: 1.TCP/IP层次模型 当然这里 ...

  5. 深入浅出讲解:php的socket通信

    对TCP/IP.UDP.Socket编程这些词你不会很陌生吧?随着网络技术的发展,这些词充斥着我们的耳朵.那么我想问:1.         什么是TCP/IP.UDP?2.         Socke ...

  6. Java和C#的socket通信相关(转)

    这几天在博客园上看到好几个写Java和C#的socket通信的帖子.但是都为指出其中关键点. C# socket通信组件有很多,在vs 使用nuget搜索socket组件有很多类似的.本人使用的是自己 ...

  7. 深入浅出讲解:php的socket通信[转]

    对TCP/IP.UDP.Socket编程这些词你不会很陌生吧?随着网络技术的发展,这些词充斥着我们的耳朵.那么我想问: 1.         什么是TCP/IP.UDP?2.         Sock ...

  8. 【转】C# Socket通信编程

    https://www.cnblogs.com/dotnet261010/p/6211900.html#undefined 一:什么是SOCKET socket的英文原义是“孔”或“插座”.作为进程通 ...

  9. PHP的socket通信原理及实现

    对TCP/IP.UDP.Socket编程这些词你不会很陌生吧?随着网络技术的发展,这些词充斥着我们的耳朵.那么我想问: 1.         什么是TCP/IP.UDP?2.         Sock ...

  10. 浅出讲解:php的socket通信

    原文地址:https://www.cnblogs.com/aipiaoborensheng/p/6708963.html 对TCP/IP.UDP.Socket编程这些词你不会很陌生吧?随着网络技术的发 ...

随机推荐

  1. 简易ATM机

    简易ATM机(代码如下): /* * 功能:简易银行系统 */package day8; import java.util.Scanner; /** * * @FengYan Huang Admini ...

  2. mysql数据库中case when 的用法

    场景1:比如说我们在数据库存了性别的字段,一般都是存0 和 1 代表男和女   然后我们会得到0和1之后在java中判断 ,很麻烦有么有?其实我们完全可以在sql中判断好之后拿来现成的.就是在sql中 ...

  3. ThreadLocal以及内存泄漏

    ThreadLocal是什么 ThreadLocal 的作用是提供线程内的局部变量,这种变量在线程的生命周期内起作用,减少同一个线程内多个函数或者组件之间一些公共变量的传递的复杂度.但是如果滥用Thr ...

  4. CodeChef Arithmetic Progressions

    https://www.codechef.com/status/COUNTARI 题意: 给出n个数,求满足i<j<k且a[j]-a[i]==a[j]-a[k] 的三元组(i,j,k)的个 ...

  5. SpringMVC学习笔记_02

    1.springmvc对多视图的支持 (1)导入xml格式视图支持的jar包   注意:springmvc本身就支持xml格式,所以不用导入其他支持的jar包了. (2)在springmvc.xml中 ...

  6. HTML中       等6种空白空格的区别

    HTML提供了5种空格实体(space entity),它们拥有不同的宽度,非断行空格( )是常规空格的宽度,可运行于所有主流浏览器.其他几种空格(       ‌‍)在不同浏览器中宽度各异.   它 ...

  7. QLabel-标签控件的应用

    label = QLabel('我是李明') #创建标签控件对象.参数:标签中要显示的文本 label.setText('我是明明') 修改标签控件显示的文本 self.label.text() 返回 ...

  8. W3C规范

    连接:https://www.w3cschool.cn/xuexiw3c/xuexiw3c-standards.html W3C 代码标准规范 由 路飞 创建, 最后一次修改 2017-01-03 W ...

  9. 阿里云服务器 ECS Linux 禁止IP 通过 SSH 登录

    这几天买的服务器老是受到黑客攻击被破解登录密码,今天修改了登录规则发现只有固定ip可以访问,其他ip即使有密码也无法登录我的服务器,但是能通过ip访问我的网站,哈哈. 限制 IP SSH 登录解决步骤 ...

  10. centos6 python 安装 sqlite 解决 No module named ‘_sqlite3′

    原文连接: http://blog.csdn.net/jaket5219999/article/details/53512071 系统red hat6.7 也即centos6.7 python3.5. ...