C# Socket编程

简介:

一、同步方式:
1.服务器端 server.cs

using System; using System.Net.Sockets; using System.Net; using System.IO; class ProgServeur { static readonly ushort port = 50000; static void Main() { IPAddress ipAddress = new IPAddress( new byte[] { 127, 0, 0, 1 } ); TcpListener tcpListener = new TcpListener( ipAddress , port ); tcpListener.Start(); // Each loop = send a file to a client. while(true) { try { Console.WriteLine( "Waiting for a client..." ); // ‘AcceptTcpClient()’ is a blocking call. The thread // continue its course only when a client is connected. TcpClient tcpClient = tcpListener.AcceptTcpClient(); Console.WriteLine( "客户端与服务器链接成功!" ); ProcessClientRequest( tcpClient.GetStream() ); Console.WriteLine( "客户端与服务器断开链接!" ); } catch( Exception e ) { Console.WriteLine( e.Message ); } } } static void ProcessClientRequest( NetworkStream networkStream ) { // Stream used to send data. StreamWriter streamWriter = new StreamWriter( networkStream ); // Stream used to read the file. StreamReader streamReader = new StreamReader( @"C:/Text/File.txt" ); // For each line of the file: send it to the client. string sTmp = streamReader.ReadLine(); try { while(sTmp != null ) { Console.WriteLine( "Sending: {0}" , sTmp ); streamWriter.WriteLine( sTmp ); streamWriter.Flush(); sTmp = streamReader.ReadLine(); } } finally { // Close streams. streamReader.Close(); streamWriter.Close(); networkStream.Close(); } } }

2.客户端 Client.cs

 using System; using System.Net.Sockets; using System.IO; class ProgClient { static readonly string host = "localhost"; static readonly ushort port = 50000; static void Main() { TcpClient tcpClient; try { // Invoking the ‘TcpClient’ constructor raises an exception // if it can’t connect to the server. tcpClient = new TcpClient( host , port ); Console.WriteLine("连接到的服务器IP地址:{0},端口号:{1}",host,port); NetworkStream networkStream = tcpClient.GetStream(); StreamReader streamReader = new StreamReader( networkStream ); try { // Each loop = a line is fetched from the server. string sTmp = streamReader.ReadLine(); while( sTmp != null ) { Console.WriteLine( "Receiving: {0}" , sTmp ); sTmp = streamReader.ReadLine(); } } finally { // Close stream. streamReader.Close(); networkStream.Close(); Console.WriteLine( "断开的服务器IP地址:{0},端口:{1}", host, port); Console.Read(); } } catch( Exception e ) { Console.WriteLine( e.Message ); return; } } }

二、异步方式
 1.服务器端 Server.cs

using System; using System.Net.Sockets; using System.Net; using System.IO; using System.Text; class ProgServeur { static readonly ushort port = 50000; static void Main() { IPAddress ipAddress = new IPAddress( new byte[] { 127, 0, 0, 1 } ); TcpListener tcpListener = new TcpListener( ipAddress, port ); tcpListener.Start(); while(true) { try { Console.WriteLine( "Main:Waiting for a client..." ); TcpClient tcpClient = tcpListener.AcceptTcpClient(); Console.WriteLine( "Main:Client connected." ); ClientRequestProcessing clientRequestProcessing = new ClientRequestProcessing( tcpClient.GetStream() ); clientRequestProcessing.Go(); } catch( Exception e ) { Console.WriteLine( e.Message ); } } } } // An instance of this class is created for each client. class ClientRequestProcessing { static readonly int bufferSize = 512; private byte [] m_Buffer; private NetworkStream m_NetworkStream; private AsyncCallback m_CallbackRead; private AsyncCallback m_CallbackWrite; // The constructor initializes : // - m_NetworkStream: stream to communicate with the client. // - m_CallbackRead : callback procedure for read. // - m_CallbackWrite: callback procedure for write. // - m_Buffer : used both for reading and writing data. public ClientRequestProcessing( NetworkStream networkStream ) { m_NetworkStream = networkStream; m_CallbackRead = new AsyncCallback( this.OnReadDone ); m_CallbackWrite = new AsyncCallback( this.OnWriteDone ); m_Buffer = new byte[ bufferSize ]; } public void Go() { m_NetworkStream.BeginRead( m_Buffer, 0 , m_Buffer.Length , m_CallbackRead , null ); } // This callback procedure is called when an asynchronous read // triggered by a call to ‘BeginRead()’ terminates. private void OnReadDone( IAsyncResult asyncResult ) { int nBytes = m_NetworkStream.EndRead(asyncResult ); // Send back the received string to the client. if( nBytes > 0 ){ string s = Encoding.ASCII.GetString( m_Buffer , 0 , nBytes ); Console.Write( "Async:{0} bytes received from client: {1}" , nBytes, s ); m_NetworkStream.BeginWrite( m_Buffer, 0 , nBytes , m_CallbackWrite , null ); } // If the client didn’t send anything, the we discard him. else{ Console.WriteLine( "Async:Client request processed." ); m_NetworkStream.Close(); m_NetworkStream = null; } } // This callback procedure is called when an asynchronous write // triggered by a call to ‘BeginWrite()’ terminates. private void OnWriteDone( IAsyncResult asyncResult ) { m_NetworkStream.EndWrite( asyncResult ); Console.WriteLine( "Async:Write done." ); m_NetworkStream.BeginRead( m_Buffer, 0 , m_Buffer.Length , m_CallbackRead , null ); } }

2.客户端 Client.cs

 using System; using System.Net.Sockets; using System.IO; class ProgClient { static readonly string host = "localhost"; static readonly ushort port = 50000; static void Main() { TcpClient tcpClient; try{ // Invoking the ‘TcpClient’ constructor raises an exception // if it can’t connect to the server. tcpClient = new TcpClient(host,port); Console.WriteLine("Connection established with {0}:{1}",host,port); // Initialize the stream to communicate with the server // available for sending and receiving data. NetworkStream networkStream = tcpClient.GetStream(); StreamWriter streamWriter =new StreamWriter( networkStream ); StreamReader streamReader =new StreamReader( networkStream ); try { string sSend = "Hi from the client!"; string sReceived; for(int i=0;i<3;i++) { // Send data to the server. Console.WriteLine( "Client -> Server :" + sSend ); streamWriter.WriteLine( sSend ); streamWriter.Flush(); // Receiving data from the server. sReceived = streamReader.ReadLine(); Console.WriteLine( "Server -> Client :" + sReceived ); } } finally{ streamWriter.Close(); streamReader.Close(); networkStream.Close(); } } catch(Exception e) { Console.WriteLine( e.Message ); return; } } }

目录
相关文章
|
5月前
|
C# 开发者
C# 一分钟浅谈:Socket 编程基础
【10月更文挑战第7天】本文介绍了Socket编程的基础知识、基本操作及常见问题,通过C#代码示例详细展示了服务器端和客户端的Socket通信过程,包括创建、绑定、监听、连接、数据收发及关闭等步骤,帮助开发者掌握Socket编程的核心技术和注意事项。
165 3
C# 一分钟浅谈:Socket 编程基础
|
2月前
|
网络协议 C# 开发工具
C#中简单Socket编程
1. 先运行服务器代码。服务器将开始监听指定的IP和端口,等待客户端连接。 1. 然后运行客户端代码。客户端将连接到服务器并发送消息。 1. 服务器接收到消息后,将回应客户端,并在控制台上显示接收到的消息。 1. 客户端接收到服务器的回应消息,并在控制台上显示。
150 15
|
5月前
|
消息中间件 网络协议 C#
C#使用Socket实现分布式事件总线,不依赖第三方MQ
`CodeWF.EventBus.Socket` 是一个轻量级的、基于Socket的分布式事件总线系统,旨在简化分布式架构中的事件通信。它允许进程之间通过发布/订阅模式进行通信,无需依赖外部消息队列服务。
C#使用Socket实现分布式事件总线,不依赖第三方MQ
|
5月前
|
网络协议 测试技术 网络安全
Python编程-Socket网络编程
Python编程-Socket网络编程
52 0
|
8月前
|
网络协议 开发者 Python
深度探索Python Socket编程:从理论到实践,进阶篇带你领略网络编程的魅力!
【7月更文挑战第25天】在网络编程中, Python Socket编程因灵活性强而广受青睐。本文采用问答形式深入探讨其进阶技巧。**问题一**: Socket编程基于TCP/IP,通过创建Socket对象实现通信,支持客户端和服务器间的数据交换。**问题二**: 提升并发处理能力的方法包括多线程(适用于I/O密集型任务)、多进程(绕过GIL限制)和异步IO(asyncio)。**问题三**: 提供了一个使用asyncio库实现的异步Socket服务器示例,展示如何接收及响应客户端消息。通过这些内容,希望能激发读者对网络编程的兴趣并引导进一步探索。
96 4
|
8月前
|
开发者 Python
Python Socket编程:不只是基础,更有进阶秘籍,让你的网络应用飞起来!
【7月更文挑战第25天】在网络应用蓬勃发展的数字时代,Python凭借其简洁的语法和强大的库支持成为开发高效应用的首选。本文通过实时聊天室案例,介绍了Python Socket编程的基础与进阶技巧,包括服务器与客户端的建立、数据交换等基础篇内容,以及使用多线程和异步IO提升性能的进阶篇。基础示例展示了服务器端监听连接请求、接收转发消息,客户端连接服务器并收发消息的过程。进阶部分讨论了如何利用Python的`threading`模块和`asyncio`库来处理多客户端连接,提高应用的并发处理能力和响应速度。掌握这些技能,能使开发者在网络编程领域更加游刃有余,构建出高性能的应用程序。
49 3
|
8月前
|
网络协议 Python
网络世界的建筑师:Python Socket编程基础与进阶,构建你的网络帝国!
【7月更文挑战第26天】在网络的数字宇宙中,Python Socket编程是开启网络世界大门的钥匙。本指南将引领你从基础到实战,成为网络世界的建筑师。
88 2
|
8月前
|
网络协议 程序员 视频直播
|
8月前
|
消息中间件 网络协议 网络安全
Python Socket编程:打造你的专属网络通道,基础篇与进阶篇一网打尽!
【7月更文挑战第26天】在网络编程领域,Python以简洁语法和强大库支持成为构建应用的首选。Socket编程为核心,实现计算机间的数据交换。
97 1
|
8月前
|
网络协议 安全 Java
Java中的网络编程:Socket编程详解
Java中的网络编程:Socket编程详解