C # socket 实例
同步客户端存储示例
下面的示例程序创建连接到服务器的客户端。 客户端使用一个同步套接字生成,因此,客户端应用程序的执行挂起,直到服务器返回响应。 应用程序将字符串发送到服务器并显示在控制台的服务器返回的字符串。
using System;
using System.Net;
using System.Net.Sockets;
using System.Text; public class SynchronousSocketClient { public static void StartClient() {
// Data buffer for incoming data.
byte[] bytes = new byte[1024]; // Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName())
//Dns是一个静态类,它从 Internet 域名系统(DNS) 检索关于特定主机的信息。
//Dns.GetHostName()获取本地计算机的主机名。
//Dns.Resolve() 将 DNS 主机名或 IP 地址解析为 IPHostEntry实例。
//类IPHostEntry 为 Internet 主机地址信息提供容器类。 IPAddress ipAddress = ipHostInfo.AddressList[0];//提供网际协议 (IP) 地址。
IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);//将网络端点表示为 IP 地址和端口号。 // Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
//InterNetwork IP 版本 4 的地址。
//Stream 支持可靠、双向、基于连接的字节流,而不重复数据,也不保留边界。
// 此类型的 Socket 与单个对方主机通信,并且在通信开始之前需要建立远程主机连接。
// Stream使用传输控制协议 (Tcp) ProtocolType和 InterNetworkAddressFamily。
// Connect the socket to the remote endpoint. Catch any errors.
try {
sender.Connect(remoteEP); Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString()); // Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>"); // Send the data through the socket.
int bytesSent = sender.Send(msg); // Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes,0,bytesRec)); // Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close(); } catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}",se.ToString());
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
} } catch (Exception e) {
Console.WriteLine( e.ToString());
}
} public static int Main(String[] args) {
StartClient();
return 0;
}
}
同步服务器端存储示例
下面的示例程序创建接收来自客户端的连接请求的服务器。 服务器使用一个同步套接字生成,因此,服务器应用程序的执行挂起,它在等待从客户端时的连接。 应用程序收到来自客户端的字符串,在控制台上显示字符串,然后回显该字符串返回给客户端。 从客户端的字符串必须包含字符串“<EOF>”用于通知消息的结尾。
using System;
using System.Net;
using System.Net.Sockets;
using System.Text; public class SynchronousSocketListener { // Incoming data from the client.
public static string data = null; public static void StartListening() {
// Data buffer for incoming data.
byte[] bytes = new Byte[1024]; // Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); // Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp ); // Bind the socket to the local endpoint and
// listen for incoming connections.
try {
listener.Bind(localEndPoint);//使 Socket 与一个本地终结点相关联。
listener.Listen(10);//将 Socket 置于侦听状态
//参数backlog这个参数涉及到一些网络的细节。在进程正理一个一个连接请求的时候,可能还存在其它的连接请求。
//因为TCP连接是一个过程,所以可能存在一种半连接的状态,有时由于同时尝试连接的用户过多,
//使得服务器进程无法快速地完成连接请求。如果这个情况出现了,服务器进程希望内核如何处理呢?
//内核会在自己的进程空间里维护一个队列以跟踪这些完成的连接但服务器进程还没有接手处理或正在进行的连接,
//这样的一个队列内核不可能让其任意大,所以必须有一个大小的上限。这个backlog告诉内核使用这个数值作为上限。
//毫无疑问,服务器进程不能随便指定一个数值,内核有一个许可的范围。这个范围是实现相关的。
//很难有某种统一,一般这个值会小30以内。 // Start listening for connections.
while (true) {
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null; // An incoming connection needs to be processed.
while (true) {
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,0,bytesRec);
if (data.IndexOf("<EOF>") > -1) {
break;
}
} // Show the data on the console.
Console.WriteLine( "Text received : {0}", data); // Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data); handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
} } catch (Exception e) {
Console.WriteLine(e.ToString());
} Console.WriteLine("\nPress ENTER to continue...");
Console.Read(); } public static int Main(String[] args) {
StartListening();
return 0;
}
}
http://msdn.microsoft.com/zh-cn/library/w89fhyex(v=vs.110).aspx
异步见链接
C # socket 实例的更多相关文章
- 网络编程基础【day09】:简单socket实例(二)
本节内容 1.概述 2.socket实例 3.总结 一.概述 之前我们只是介绍了soket的概念和一些逻辑图表,下面我们来看看,socket的客户端和服务端到底是怎么用的? 二.socket实例 2. ...
- java tcp socket实例
java tcp socket实例 2011-04-20 13:58 2364人阅读 评论(1) 收藏 举报 socketjavatcpthreadserverclass package com.ne ...
- socket实例2
第二个实例创建一个java工程,基于tomcat服务器,程序运行时会启动客户端,实现了一个客户端向其他的客户端发送即时信息的功能 MainWindow.java package com.jikexue ...
- python socket实例练习
Web Server是基于Socket编程,又称之为网络编程,socket是网络编程接口,socket可以建立网络连接,读数据,写数据.socket模块定义了一些常量参数,用来指定socket的的地址 ...
- py测试一个Socket实例
本实例旨在了解py和socket的一些相关知识. 1.服务器端搭建py监听程序. 在客户端搭建python,linux默认自带了python2.7,先不管安装了. 接着编写socket程序,可以在本地 ...
- python socket实例
1.客户端向服务端发送 #coding:utf-8 '''客户端''' import socket khd=socket.socket() #声明socket类型,同时生产socket连接对象 khd ...
- 简单的php socket 实例
server: <?php set_time_limit(0); $ip = '127.0.0.1'; $port = 8888; // 1. 创建 if( ($sock = socket_cr ...
- socket实例1
第一个例子创建了一个java工程,用来测试Socket的连接功能,通过浏览器可访问,地址为:127.0.0.1:端口号 MyServerSocket.java, package com.jikexue ...
- java Socket实例
可以实现客户端与服务端双向通信,支持多客户端连接,客户端断开连接,服务端不会出现异常 服务端代码: package com.thinkgem.jeesite.modules.socketTest.de ...
随机推荐
- 学习笔记16_页面缓存/进程外Session
*页面缓存:适用于访问量较高的网站 <%@OutputCache Duration="15"//缓存15秒 VaryByParam='*' //请求的任何一处发生改变,缓存 ...
- 在mac上用parallels创建双windows虚拟机调试windows驱动
先创建两个windows 7 虚拟机,一个装windbg作为调试机,一个被调试 1 调试机 1 先装windbg https://developer.microsoft.com/en-us/windo ...
- [考试反思]1105csp-s模拟测试102: 贪婪
还是有点蠢... 多测没清空T3挂40...(只得了人口普查分20) 多测题要把样例复制粘两遍自测一下防止未清空出锅. 然而不算分... 其实到现在了算不算也不重要了吧... 而且其实T3只考虑最长路 ...
- Hbase与Oracle的比较
http://blog.csdn.net/lucky_greenegg/article/details/47070565 转自:http://www.cnblogs.com/chay1227/arch ...
- ASP.NET Core Blazor 用Inspinia静态页模板搭建简易后台(实现菜单选中)
Blazor 是一个用于使用 .NET 生成交互式客户端 Web UI 的框架: 使用 C# 代替 JavaScript 来创建丰富的交互式 UI. 共享使用 .NET 编写的服务器端和客户端应用逻辑 ...
- LeetCode刷题总结-数组篇(下)
本期讲O(n)类型问题,共14题.3道简单题,9道中等题,2道困难题.数组篇共归纳总结了50题,本篇是数组篇的最后一篇.其他三个篇章可参考: LeetCode刷题总结-数组篇(上),子数组问题(共17 ...
- python——直接插入排序
直接插入排序 直接插入排序原理 直接插入排序过程 代码 时间复杂度分析 排序稳定性
- java笔试面试第二天
没想到第二次面试到了第二周,也是我在上海找工作的第二周,说实话,没有真本事找工作是真的难,虽然正在召开的十九大上,大大们纷纷表态国力正盛,经济稳步增长,就业压力逐渐缓解,但是社会终究是社会,要么靠实力 ...
- 创建基于OData的Web API - Knowledge Builder API, Part IV: Write Controller
基于上一篇<创建基于OData的Web API - Knowledge Builder API, Part III:Write Model and Controller>,新创建的ODat ...
- T-SQL Part IV: ORDER BY
ORDER BY 返回一个Cursor,并不返回结果集.而试图将Cursor作为输入将产生了错误. 所以,下列的SQL语句将产生错误: SELECT VerID, IsComplete VerID, ...