I don't know what the name should be. I just want to rewrite the send METHOD OF THE tcpclient client attribute when writing tcpclient, which is actually the send method of socket. Because I want to exchange data with strings, this byte [] conversion is too troublesome.
For example, sending and receiving is troublesome when there is no rewrite.
Tcpclient Client = Listener. accepttcpclient ();
String Buff = " Connection established \ r \ n " ;
Byte [] B = System. Text. encoding. Default. getbytes (buff );
Client. Client. Send (B );
Networkstream mynetworkstream = Client. getstream ();
Byte [] Bytes = New Byte [ 1024 ];
Int Bytesread = Mynetworkstream. Read (bytes, 0 , Bytes. Length );
String Getstr = Encoding. Default. getstring (bytes, 0 , Bytesread );
If you define a class myTcpclient inherited fromTcpclient, but the listener. accepttcpclient (); type isTcpclient, cannot be converted to myTcpclient.
MyTcpclient client = (myTcpclient) Listener. accepttcpclient (); is not allowed.
Then, if I directly define myTcpclient has the send Method
/// <Summary>
/// Send server information
/// </Summary>
/// <Param name = "MSG"> </param>
Public void send (string MSG)
{
Byte [] B = system. Text. encoding. Default. getbytes (MSG );
Tcp. client. Send (B );
}
It cannot be used here.
The alternative method is aggregation.
DetailsCode Yes /// <Summary>
/// Tcpclient
/// The value is new tcplistener (). accepttcpclient ()
/// </Summary>
Public Class Mytcpclient
{
Tcpclient TCP { Get ; Set ;}
Networkstream mynetworkstream;
Public BoolConnected {Get{ReturnTCP. connected ;}}
/// <Summary>
/// Send Server Information
/// </Summary>
/// <Param name = "MSG"> </param>
Public Void Send ( String MSG)
{
Byte [] B = System. Text. encoding. Default. getbytes (MSG );
Tcp. client. Send (B );
}
Public VoidClose ()
{
Mynetworkstream. Close ();
TCP. Close ();
}
/// <Summary>
/// Receive client data
/// </Summary>
/// <Returns> </returns>
Public String Received ()
{
Byte [] Bytes = New Byte [ 1024 ];
Int Bytesread = Mynetworkstream. Read (bytes, 0 , Bytes. Length );
String Getstr = Encoding. Default. getstring (bytes, 0 , Bytesread );
Return Getstr;
}
Mytcpclient (tcpclient TCP)
{
TCP=TCP;
Mynetworkstream=TCP. getstream ();
}
/// <Summary>
/// Reload equals
/// </Summary>
/// <Param name = "TCP"> </param>
/// <Returns> </returns>
Public Static Implicit Operator Mytcpclient (tcpclient TCP)
{
Return New Mytcpclient (TCP );
}
}
In this way, it is not an alternative to replace tcpclient with mytcpclient.
When usingTcplistener listener= Null;
Listener= NewTcplistener (8009);
Listener. Start ();
While ( True )
{
Mytcpclient Client = Listener. accepttcpclient ();
Client. Send (datetime. Now. tostring () + " Connection established \ r \ n " );
Console. Write (client. Received ());
Client. Close ();
}
Listener. Stop ();
This is too simple: P