TCP(TransmissionControl Protocol)传输控制协议。

是一种可靠的、面向连接的协议(eg:打电话)、传输效率低全双工通信(发送缓存&接收缓存)、面向字节流。使用TCP的应用:Web浏览器;电子邮件、文件传输程序。

TCP编程的服务器端一般步骤是:

  1、创建一个socket,用函数socket()。

  2、设置socket属性。

  3、绑定本机的IP地址、端口等信息到socket上,用函数bind()。

  4、开启监听,用函数listen()。

5、接收客户端上来的连接,用函数accept()。

6、通过accept()返回相应客户端的socket建立专用的通信通道。

  7、收发数据,用函数send()和recv(),或者read()和write()。

  8、关闭网络连接。

  9、关闭监听。

TCP编程的客户端一般步骤是:

  1、创建一个socket,用函数socket()。

  2、设置socket属性。 

  3、设置要连接的对方的IP地址和端口等属性。

  4、连接服务器,用函数connect()。

  5、收发数据,用函数send()和recv(),或者read()和write()。

  6、关闭网络连接。 

---------------------
作者:subin_iecas
来源:CSDN
原文:https://blog.csdn.net/subin_iecas/article/details/80289513


下面是一个简单的TCP的通信程序源码

主要功能是模拟一个群聊,当多个客户端连接进来后,任意一个客户端发送的消息都将被服务器端接收并群发给所有客户端


服务器端:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading; namespace _037_test
{
class Program
{
static void Main(string[] args)
{
Server s = new Server("192.168.0.105", );
s.Start();
}
}
}

Program.CS

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading; namespace _037_test
{
class Server
{
Socket serverSock;
List<Socket> clientList = new List<Socket>();
public Server(string ip, int port)
{
//创建socket套接字
serverSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//检测ip地址是否有误
IPAddress ipAdd;
if (!IPAddress.TryParse(ip, out ipAdd))
{
Console.WriteLine("ip有误,服务器创建失败");
return;
}
//绑定ip地址和端口;
IPEndPoint point = new IPEndPoint(ipAdd, port);
serverSock.Bind(point);
//无限监听接收
serverSock.Listen(); } public void Start()
{
Thread th = new Thread(AcceptClient);
th.Start();
SendToAll();
} public void AcceptClient()
{
Console.WriteLine("等待连接");
while (true)
{
Socket client = serverSock.Accept();//等待接收用户的连接,并返回连接成功的用户
IPEndPoint clientPoint = client.RemoteEndPoint as IPEndPoint;//获取所连接的用户的ip
Console.WriteLine(clientPoint.Address+"已连接");
clientList.Add(client);
Thread clientT = new Thread(ReceiveMessage);
clientT.Start(client);
}
} public void SendToAll()
{
while (true)
{
string message = "管理员:"+Console.ReadLine();
byte[] messageBytes = Encoding.Default.GetBytes(message);
for (int i = ; i < clientList.Count; i++)
{
try
{
clientList[i].Send(messageBytes);
}
catch (SocketException)
{
Console.WriteLine("有一个客户端下线");
clientList.RemoveAt(i);
i--;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
} public void ReceiveMessage(object obj)
{
while (true)
{
Socket client = obj as Socket;//将线程的start方法传入的obj转回socket类型
byte[] messageBytes = new byte[ * ];//数据容器
try
{
int num = client.Receive(messageBytes);//receive方法返回字节长度,并把内容存在传入的数组中
IPEndPoint clientPoint = client.RemoteEndPoint as IPEndPoint;//获取所连接的用户的ip
Console.WriteLine(clientPoint.Address+":" + Encoding.Default.GetString(messageBytes, , num)); //服务器端负责将从客户端收到的消息转发给所有客户端
string message = clientPoint.Address + ":" + Encoding.Default.GetString(messageBytes, , num);
foreach (var item in clientList)
{
if (item!=client)
{
item.Send(Encoding.Default.GetBytes(message));
}
}
}
catch (Exception)
{
Console.WriteLine("有一个客户端离开");
clientList.Remove(client);
break;
}
} }
}
}

Server.CS


客户端:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading; namespace _038_test
{
class Program
{
static void Main(string[] args)
{
Client c = new Client("192.168.0.105", );
c.Start();
}
}
}

Program.CS

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading; namespace _038_test
{
class Client
{
Socket clientSock;
public Client(string ip, int port)
{
clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
IPEndPoint point = new IPEndPoint(IPAddress.Parse(ip), port);
clientSock.Connect(point);
}
catch (Exception)
{
Console.WriteLine("服务器没有开启");
return;
} Console.WriteLine("已连接服务器");
} public void Start()
{
Thread th = new Thread(SendMessage);
th.Start();
ReceiveMessage();
} public void SendMessage()
{
try
{
while (true)
{
string message = Console.ReadLine();
byte[] messageBytes = Encoding.Default.GetBytes(message);
clientSock.Send(messageBytes);
}
}
catch (Exception)
{
Console.WriteLine("服务器断开");
return;
} } public void ReceiveMessage()
{
try
{
while (true)
{
byte[] messageBytes = new byte[ * ];
int num = clientSock.Receive(messageBytes);
Console.WriteLine(Encoding.Default.GetString(messageBytes, , num));
}
}
catch (Exception)
{
Console.WriteLine("服务器断开");
return;
}
} }
}

Client.CS


运行结果:

C#socket编程之实现一个简单的TCP通信的更多相关文章

  1. Linux socket编程示例(最简单的TCP和UDP两个例子)

    一.socket编程 网络功能是Uinux/Linux的一个重要特点,有着悠久的历史,因此有一个非常固定的编程套路. 基于TCP的网络编程: 基于连接, 在交互过程中, 服务器和客户端要保持连接, 不 ...

  2. 利用JSP编程技术实现一个简单的购物车程序

    实验二   JSP编程 一.实验目的1. 掌握JSP指令的使用方法:2. 掌握JSP动作的使用方法:3. 掌握JSP内置对象的使用方法:4. 掌握JavaBean的编程技术及使用方法:5. 掌握JSP ...

  3. 27、通过visual s'tudio 验证 SOCKET编程:搭建一个TCP服务器

    本文就是在windows下进行socket编程,搭建一个TCP客户端. 在visual studio下编程,首先在windows下进行初始化(这点在linux下是不需要的): /* 初始化 Winso ...

  4. 一个简单的tcp代理实现

    There are a number of reasons to have a TCP proxy in your tool belt, bothfor forwarding traffic to b ...

  5. 【实验 1-1】编写一个简单的 TCP 服务器和 TCP 客户端程序。程序均为控制台程序窗口。

    在新建的 C++源文件中编写如下代码. 1.TCP 服务器端#include<winsock2.h> //包含头文件#include<stdio.h>#include<w ...

  6. Node.js实战14:一个简单的TCP服务器。

    本文,将会展示如何用Nodejs内置的net模块开发一个TCP服务器,同时模拟一个客户端,并实现客户端和服务端交互. net模块是nodejs内置的基础网络模块,通过使用net,可以创建一个简单的tc ...

  7. Linux下的C Socket编程 -- server端的简单示例

    Linux下的C Socket编程(三) server端的简单示例 经过前面的client端的学习,我们已经知道了如何创建socket,所以接下来就是去绑定他到具体的一个端口上面去. 绑定socket ...

  8. 【Java编程】建立一个简单的JDBC连接-Drivers, Connection, Statement and PreparedStatement

    本blog提供了一个简单的通过JDBC驱动建立JDBC连接例程.并分别通过Statement和PreparedStatement实现对数据库的查询. 在下一篇blog中将重点比較Statement与P ...

  9. socket编程之中的一个:计算机网络基础

    在開始学习网络之前先复习下计算机网络基础吧. 鲁迅说,天下文章一大抄.看你会炒不会炒,基础知识就抄抄书吧. 一 分层模型 1 为什么分层 为了简化网络设计的复杂性.通讯协议採用分层结构.各层协议之间既 ...

随机推荐

  1. xcode 10 模拟器报错

    xcode 10(也可能是任意版本)run 模拟器时,发现会报下面的错误. This app could not be installed at this time.Could not access ...

  2. 零python基础--爬虫实践总结

    网络爬虫,是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本. 爬虫主要应对的问题:1.http请求 2.解析html源码 3.应对反爬机制. 觉得爬虫挺有意思的,恰好看到知乎有人分享的一个爬虫 ...

  3. Azure基础(二)- 核心云服务 - Azure简介

    Azure fundamentals - Core Cloud Services - Introduction to Azure Learn what Microsoft Azure is and h ...

  4. windows之电脑开机出现 this product is covered by one or more of the following prtents

    电脑开机出现 this product is covered by one or more of the following prtents 有次意外断电后就每次都出现这个提示,然后要等检查完才能进入 ...

  5. 【错误总结1:unity StartCoroutine 报 NullReferenceException 错误】

    今天在一个项目中,写了一个单例的全局类,该类的作用是使用协程加载场景.但在StartCoroutine 这一步报了NullReferenceException 的错.仔细分析和搜索之后,得到错误原因. ...

  6. 执行python解释器的两种方式

    执行python解释器的两种方式 1.交互式 python是高级语言,是解释型语言,逐行翻译,写一句翻译一句 print ('hello world') 2.命令行式 python和python解释器 ...

  7. liunx驱动----系统滴答时钟的使用

    2019-3-12系统滴答定时器中断使用 定义一个timer ​​ 其实就是使用系统的滴答定时器产生一个中断. 初始化timer init_timer函数 实现如下 void fastcall ini ...

  8. redis 在 php 中的应用(Hash篇)

    本文为我阅读了 redis参考手册 之后结合 博友的博客 编写,注意 php_redis 和 redis-cli 的区别(主要是返回值类型和参数用法) Redis hash 是一个string类型的f ...

  9. NOIP2015题解

    D1T1模拟 #include<bits/stdc++.h> #define re(i,l,r) for(int i=(l);i<=(r);i++) using namespace ...

  10. GoldenGate HANDLECOLLISIONS参数使用说明

    HANDLECOLLISIONS在官方文档上的说明: 使用HANDLECOLLISIONS和NOHANDLECOLLISIONS参数来控制在目标上应用SQL时,Replicat是否尝试解决重复记录和缺 ...