c#(Socket)同步套接字代码示例_C#教程

同步客户端套接字示例  

下面的示例程序创建一个连接到服务器的客户端。该客户端是用同步套接字生成的,因此挂起客户端应用程序的执行,直到服务器返回响应为止。该应用程序将字符串发送到服务器,然后在控制台显示该服务器返回的字符串。

C#
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())
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
// Create a TCP/IP  socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// 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>”,
以发出表示消息结尾的信号。

 

C#
 复制代码

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);
listener.Listen(10);
// 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;
}
}

时间: 2024-08-01 19:50:09

c#(Socket)同步套接字代码示例_C#教程的相关文章

c#(Socket)异步套接字代码示例_C#教程

异步客户端套接字示例   下面的示例程序创建一个连接到服务器的客户端.该客户端是用异步套接字生成的,因此在等待服务器返回响应时不挂起客户端应用程序的执行.该应用程序将字符串发送到服务器,然后在控制台显示该服务器返回的字符串. C# using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Text; // State object for receiving dat

c#(Socket)同步套接字代码示例

同步客户端套接字示例 下面的示例程序创建一个连接到服务器的客户端.该客户端是用同步套接字生成的,因此挂起客户端应用程序的执行,直到服务器返回响应为止.该应用程序将字符串发送到服务器,然后在控制台显示该服务器返回的字符串. C# using system; using system.Net; using system.Net.Sockets; using system.Text; public class SynchronousSocketClient { public static void S

C#实现冒泡排序算法的代码示例_C#教程

1.原理:从数组的第一个位置开始两两比较array[index]和array[index+1],如果array[index]大于array[index+1]则交换array[index]和array[index+1]的位置,止到数组结束; 从数组的第一个位置开始,重复上面的动作,止到数组长度减一个位置结束; 从数组的第一个位置开始,重复上面的动作,止到数组长度减二个位置结束; ....2.时间复杂度:O(N²),进行了(n-1)*(n-2)....=n*(n-1)/2次比较和约比较次数一半的交换

用C#写的ADSL拨号程序的代码示例_C#教程

<!--StartFragment-->ADSL自动拨号类,前提是在系统中已经有了一个宽带拨号连接 调用代码: RASDisplay ras = new RASDisplay(); ras.Disconnect();//断线 ras.Connect("adsl");//拨号  复制代码 代码如下: using System;  using System.Runtime.InteropServices;  public struct RASCONN  {      publi

iOS - Socket 网络套接字

1.Socket 套接字 所谓 Socket,通常称为 "套接字",网络应用程序通过套接字向网络发送请求或者应答网络请求.Socket 通常用于描述 IP 地址和端口,是应⽤层与 TCP/IP 协议族通信的中间软件抽象层,它是一组接口,是一个通信链的句柄,可以用来实现不同虚拟机或者不同计算机之间的通信.在设计模式中,Socket 其实就是一个门面模式,它把复杂的 TCP/IP 协议族隐藏在 Socket 接⼝后面. Socket 起源于 Unix,而 Unix/Linux 基本哲学之一

C语言求矩阵的各列元素之和的代码示例_C 语言

问题描述:统计一个矩阵的各列元素之和.矩阵各元素为整数且绝对值不超过100.要求输入:有多个测试用例,每个测试用例的第一行是空格分隔的两个正整数n和m( 1 < n, m < 80 ),接下来的n行每行有m个空格分隔的整数,组成一个n*m的矩阵.最后一个测试用例n=0 m=0不用处理.要求输出:对每个测试用例,输出一行整数(空格分隔),顺序表示从第1列至第m列的各列元素之和.输入示例: 3 5 1 1 1 2 -1 0 1 0 7 4 0 2 0 -8 -4 2 2 1 1 0 1 0 0 输

C#实现的Win32控制台线程计时器功能示例_C#教程

本文实例讲述了C#实现的Win32控制台线程计时器功能.分享给大家供大家参考,具体如下: 在C#中提供了三种类型的计时器: 1.基于 Windows 的标准计时器(System.Windows.Forms.Timer) 2.基于服务器的计时器(System.Timers.Timer) 3.线程计时器(System.Threading.Timer) 一.基于 Windows 的标准计时器(System.Windows.Forms.Timer) 首先注意一点就是:Windows 计时器是为单线程环境

python原始套接字编程示例分享_python

下面开始构造HTTP数据包, IP层和TCP层使用python的Impacket库,http内容自行填写. 复制代码 代码如下: #!/usr/bin/env python #-------------------------------------------------------------------------------# Name:     raw_http.py# Purpose:       construct a raw http get packet## Author:  

C++、python和go语言实现的简单客户端服务器代码示例_C 语言

工作中用到了C/S模型,所做的也无非是给服务器发数据,但开发阶段会遇到程序自身的回环测试,需要用到简单的服务端以便验证数据发送的正确性. 写软件用C++,跑测试用python,这段时间也刚好看go语言,所以都要有demo.以下三组程序实现的功能相同,这里一起做下总结. 一.C++实现 Boost.Asio是一个跨平台的C++库,它用现代C++方法为网络和底层I/O程序提供了一致的异步I/O模型. 为了跨平台,我用boost库实现,具体如下. 服务端代码: 复制代码 代码如下: /*      F