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

同步客户端套接字示例

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

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;
}
}

(0)

相关推荐

  • C#中Socket通信用法实例详解

    本文实例讲述了C#中Socket通信用法.分享给大家供大家参考.具体如下: 一.UDP方式: 服务器端代码: static void Main(string[] args) { int recv; byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//定义一网络端点 Socket newsock = new Socket(AddressFamily.InterNetwork, S

  • C#在Unity游戏开发中进行多线程编程的方法

    在这之前,有很多人在质疑Unity支不支持多线程,事实上Unity是支持多线程的.而提到多线程就要提到Unity非常常用的协程,然而协程并非真正的多线程.协程其实是等某个操作完成之后再执行后面的代码,或者说是控制代码在特定的时机执行.而多线程在Unity渲染和复杂逻辑运算时可以高效的使用多核CPU,帮助程序可以更高效的运行.本篇主要介绍在Unity中如何使用多线程. 首先引入C#中使用多线程的类库 using System.Threading; 创建线程实例的四种方式 一.线程执行无参方法 构造

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

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

  • C#中Socket与Unity相结合示例代码

    前言 初步接触了Socket,现使其与Unity相结合,做成一个简单的客户端之间可以互相发送消息的一个Test.下面话不多说了,来一起看看详细的介绍吧. 方法如下: 首先,是服务端的代码. 创建一个连接池,用于存储客户端的数量. using System; using System.Net; using System.Net.Sockets; using System.Collections; using System.Collections.Generic; namespace Server

  • C#实现的Socket服务器端、客户端代码分享

    服务端: using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; namespace Server { class Program { static void Main(string[] args) { Socket server = new Socket(AddressFamily.InterNetwork, SocketType

  • C#实现Socket通信的解决方法

    本文以实例详述了C#实现Socket通信的解决方法,具体实现步骤如下: 1.首先打开VS新建两个控制台应用程序: ConsoleApplication_socketServer和ConsoleApplication_socketClient.   2.在ConsoleApplication_socketClient中输入以下代码: using System; using System.Collections.Generic; using System.Linq; using System.Tex

  • C#使用Socket发送和接收TCP数据实例

    本文实例讲述了Asp.net中C#使用Socket发送和接收TCP数据的方法,分享给大家供大家参考.具体实现方法如下: 具体程序代码如下: 复制代码 代码如下: using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; namespace ConsoleApplication1 {     public static class So

  • C# Socket网络编程实例

    本文实例讲述了C# Socket网络编程技巧.分享给大家供大家参考.具体分析如下: 客户端要连接服务器:首先要知道服务器的IP地址.而服务器里有很多的应用程序,每一个应用程序对应一个端口号 所以客户端想要与服务器中的某个应用程序进行通信就必须要知道那个应用程序的所在服务器的IP地址,及应用程序所对应的端口号 TCP协议:安全稳定,一般不会发生数据丢失,但是效率低.利用TCP发生数据一般经过3次握手(所有效率低,自己百度三次握手) UDP协议:快速,效率高,但是不稳定,容易发生数据丢失(没有经过三

  • C#使用Protocol Buffer(ProtoBuf)进行Unity中的Socket通信

    首先来说一下本文中例子所要实现的功能: 基于ProtoBuf序列化对象 使用Socket实现时时通信 数据包的编码和解码 下面来看具体的步骤: 一.Unity中使用ProtoBuf 导入DLL到Unity中, 创建网络传输的模型类: using System; using ProtoBuf; //添加特性,表示可以被ProtoBuf工具序列化 [ProtoContract] public class NetModel { //添加特性,表示该字段可以被序列化,1可以理解为下标 [ProtoMem

  • C#之Socket操作类实例解析

    本文展示了一个C#的Socket操作类的完整实例,并附带了用法说明,分享给大家供大家参考之用.具体方法如下: 主要功能代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Collections; using System.Net; using System.Runtime.Serializ

随机推荐