A preliminary study on C # network programming

Source: Internet
Author: User
Tags readline socket

We know that one of the differences between C # and C + + is that he does not have a class library, and the class library used is. NET Framework, the class Library--. NET Framework SDK. Two namespaces are provided for network programming in the. Net FrameWork SDK: "System.Net" and "System.Net.Sockets". C # is the network traffic through the classes and methods encapsulated in these two namespaces.

First we explain some of the concepts that are often encountered in network programming: Synchronization (Synchronous), Asynchrony (asynchronous), blocking (block), and Non-blocking (Unblock):

Synchronization means that when the sender sends the packet, it does not wait for the recipient to respond, and then sends the next packet. Asynchronous mode is when the sender sends a packet and waits until the receiver responds before sending the next packet. A blocking socket is a network call that executes this socket and is not returned until the call succeeds, otherwise this set of words is blocked on the network call, such as calling the StreamReader class's Readlin () method to read the data in the network buffer, if no data arrives when the call is made, The Readlin () method is then hung on the call until some data is read and the function call returns, rather than the blocking socket, which is immediately returned when the network call to the socket is executed, regardless of success. The Readlin () method of the StreamReader class is also invoked to read the data in the network buffer, returning immediately, regardless of whether it is read or not, rather than hanging on this function call all the time. In the development of Windows network communication software, the most common method is asynchronous non-blocking socket. Generally speaking of C/s (client/server) structure of the software used in the way is asynchronous non-blocking mode.

In fact, in C # for network programming, we do not need to know what synchronous, asynchronous, blocking and non-blocking principles and working mechanisms, because these mechanisms have already been encapsulated in the. Net Framewrok SDK. Below we use C # to open a specific network program to illustrate the problem.

A The program design and operating environment introduced in this paper

(1). Microsoft Windows 2000 Server Edition

(2). Net Framework SDK Beta 2 version

Two Key steps and solutions for server-side programming:

In the procedure that is accepted below, we are using the way of asynchronous blocking.

(1). First, create a "TcpListener" object on the given port to listen for requests on the network. When a connection request is received, an instance of the socket used to process an access connection request is generated by calling the "AcceptSocket" method of the "TcpListener" object. Here is the specific implementation code:

//创建一个tcpListener对象,此对象主要是对给定端口进行侦听
tcpListener = new TcpListener ( 1234 ) ;
//开始侦听
tcpListener.Start ( ) ;
//返回可以用以处理连接的Socket实例
socketForClient = tcpListener.AcceptSocket ( ) ;

(2). Accept and send client data:

At this point the socket instance has been generated, if there is a request on the network, after the request passes, the socket instance constructs a "NetworkStream" object, and the "NetworkStream" object provides the underlying data stream for network access. We implement access to the "NetworkStream" object through the two classes "StreamReader" and "StreamWriter" encapsulated in the namespace "System.IO". where the ReadLine () method in the "StreamReader" class reads one line of characters from the "NetworkStream" Object, the WriteLine () method in the "StreamWriter" class is to "NetworkStream" Writes a string to a line in an object. In order to implement the transmission of strings on the network, the following is the specific implementation code:

try
{
//如果返回值是"true",则产生的套节字已经接受来自远方的连接请求
if ( socketForClient.Connected )
{
ListBox1.Items.Add ( "已经和客户端成功连接!" ) ;
while ( true )
{
//创建networkStream对象通过网络套节字来接受和发送数据
networkStream = new NetworkStream ( socketForClient ) ;
//从当前数据流中读取一行字符,返回值是字符串
streamReader = new StreamReader ( networkStream ) ;
string msg = streamReader.ReadLine ( ) ;
ListBox1.Items.Add ( "收到客户端信息:" + msg ) ;
streamWriter = new StreamWriter ( networkStream ) ;
if ( textBox1.Text != "" )
{
ListBox1.Items.Add ( "往客户端反馈信息:" + textBox1.Text ) ;
//往当前的数据流中写入一行字符串
streamWriter.WriteLine ( textBox1.Text ) ;
//刷新当前数据流中的数据
streamWriter.Flush ( ) ;
}
}
}
}
catch ( Exception ey )
{
MessageBox.Show ( ey.ToString ( ) ) ;
}

(3). Finally, don't forget to close the stream, stop listening on the network, and close the section words as follows:

//关闭线程和流
networkStream.Close ( ) ;
streamReader.Close ( ) ;
streamWriter.Close ( ) ;
_thread1.Abort ( ) ;
tcpListener.Stop ( ) ;
socketForClient.Shutdown ( SocketShutdown.Both ) ;
socketForClient.Close ( ) ;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.