C # TCP / IP server and client

Server
the using the System;
the using the System.Collections.Generic;
the using the System.Text;
the using the System.Threading;
the using the System.Net.Sockets;
the using the System.Net;

namespace TcpIpServer
{
class TcpIpServerEx
{
public RemoteEndPoint the EndPoint {GET; Private SET;} // current client network nodes

thread threadwatch = null; // the client is responsible for monitoring the thread
socket socket = null; // the client is responsible for monitoring socket
// Dictionary <ip and port, socket> that define a set, store customer end information
public the Dictionary <the EndPoint, the Socket> DIC = new new the Dictionary <the EndPoint, the Socket> {};

Private the StringBuilder the StringBuilder new new MSG = ();
public String Msg
{
GET msg.ToString {return ();}
Private SET
{
msg.AppendLine (value);
Console.WriteLine (value + "\ R & lt \ n-");
}

}

Private TcpIpServerEx () {}
public TcpIpServerEx (int Port = 11000)
{
// defines a socket to listen for client sent message contains three parameters (IP4 addressing protocol, the streaming connection, Tcp protocol)
Socket new new = the Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

// port number and IP address bindings to the network node Point
the IPEndPoint the IPEndPoint new new Point = (IPAddress.Any, port); // set the server port, IP is the IP network where the present procedure the PC

// network node snooping binding
Socket.bind (Point);

/ / a socket listen queue length is limited to 20
socket.Listen (20);

// create a listener thread
threadwatch = new new the thread (watchconnecting);

// the form of threads to be synchronized with the background, along with the main thread ends The end
threadwatch.IsBackground = to true;

// start the thread
threadwatch.Start ();

After starting the thread // display the corresponding prompt
Msg = ( "client begins listening for information coming!" + "\ R & lt \ n-");
}

// listening client requests sent
Private void watchconnecting ()
{
the Socket Connection = null;
the while (to true) // continuously monitor client to request
{
the try
{
Connection socket.Accept = ();
}
the catch (Exception EX)
{
Msg = (ex.Message); // tips listening sockets abnormal
BREAK;
}

// allow customers to display "connection successful" message
string sendmsg = + connection.RemoteEndPoint "connected to the server the success of your IP is!";
byte [] arrSendMsg = Encoding.UTF8.GetBytes (sendmsg);
connection .send (arrSendMsg);


RemoteEndPoint = connection.RemoteEndPoint; // client network node number
Msg = ( "success", "client connection establishment \ t \ n!" + RemoteEndPoint +);// display connection with the client
dic.Add (RemoteEndPoint, connection); // add client information


// create a communication thread
ParameterizedThreadStart PTS = new new ParameterizedThreadStart (recv);
the Thread the Thread = new new the Thread (PTS);
thread.IsBackground = to true; // set the background thread, the main thread exits with the exit
thread.Start (connection); // start the thread
}
}

///
/// receive information sent by the client
///
/// client socket object
private void recv (Object socketclientpara)
{

the Socket SocketServer socketclientpara aS = the Socket;
the while (to true)
{
// Create a memory buffer size is 1024 * 1024 bytes i.e. 1M
byte [] = arrServerRecMsg new new byte [1024 * 1024];
// will the received information is stored into a memory buffer, and returns the byte length of the array of
the try
{
socketServer.Receive length = int (arrServerRecMsg);

// machine received byte array into a human readable string
string strSRecMsg = Encoding.UTF8.GetString (arrServerRecMsg, 0 , length);

character to be transmitted // string information attached to the text box txtMsg
Msg = ( "client:" + GetCurrentTime () + socketServer.RemoteEndPoint + " message:" + strSRecMsg + "\ R & lt \ n-");
}
the catch (Exception EX)
{
Msg = ( "client:" + GetCurrentTime () + socketServer.RemoteEndPoint + " has been disconnected" + "\ r \ n" ); // listening socket prompt abnormal
//listBoxOnlineList.Items.Remove(socketServer.RemoteEndPoint.ToString ()); // remove disconnected from the listbox client
socketServer.Close (); accept // out before closing and client socket communication
break;
}
}


}


// get the current system time
Private GetCurrentTime String ()
{
string timeStr = System.DateTime.Now.ToString ( "yyyy, MM month when the date dd hh mm ss a fff milliseconds.");
return of TIMESTR;
}

/// <Summary>
/// send information to the client
// / </ Summary>
/// <param name = "smallname"> </ param>
/// <param name = "SENDMSG"> information to be transmitted </ param>
public void SentMsg (endPoint, the EndPoint, String SENDMSG)
{

byte [] bytes = System.Text.Encoding.UTF8.GetBytes (sendMsg ); // the information to be transmitted into a byte array, because Socket transmitting data in the form of bytes transmitted
dic [endPoint] .Send ( bytes); // send data
"message:" Msg = (GetCurrentTime () SENDMSG + + + + endPoint, "\ R & lt \ n-");
}
}
}

the using the System;
namespace TcpIpServer
{
class Program
{
static void Main(string[] args)
{
S = new new TcpIpServerEx TcpIpServerEx ();
the while (to true)
{
String strSend Console.ReadLine = ();
IF (strSend == "Exit") BREAK;
Console.WriteLine ( "s.dic.Count:" + s.dic. COUNT);
IF (s.dic.Count> 0)
{
s.SentMsg (s.RemoteEndPoint, strSend);
}
}
}
}
}
client
the using the System;
the using the System.Collections.Generic;
the using the System.Text;
the using the System. threading;
a using System.Net.Sockets;
a using System.Net;

namespace TcpIpClint
{
public class TcpIpClintEx
{
// create a client socket and a request is responsible for monitoring the server thread
thread threadclient = null;
Socket = null the Socket;
List <the IPEndPoint> = mlist new new List <the IPEndPoint> ();
Private the StringBuilder the StringBuilder new new MSG = ();
public String Msg
{
GET msg.ToString {return ();}
Private SET
{
msg.AppendLine (value );
Console.WriteLine (value + "\ R & lt \ n-");
}
}

public TcpIpClintEx (String IP, Port = 11000 int)
{
// definition of a socket listener
socket = new socket (AddressFamily.InterNetwork, SocketType.Stream , ProtocolType.Tcp);
// the acquired IP address and port number on the network node binding
the IPEndPoint the IPEndPoint new new Point = (IPAddress.Parse (IP), port);
Msg = "connecting to server" + ip + ": "Port +;

the try
{
// the client socket connected to the network node, with the connect
Socket.connect (Point);
}
the catch (Exception)
{
Msg = ( "connection failed \ R & lt \ n-");
return;
}

threadclient the Thread new new = (the recv);
threadclient.IsBackground = to true;
threadclient.Start ();
}

@ a method of receiving information sent by the server
Private void the recv () //
{
the while (to true) // server continuously monitors messages sent by
{
the try
{
// definition of a 1M buffer memory for temporary storage the received message
byte [] = arrRecvmsg new new byte [1024 * 1024];

// the client socket received data into the memory buffer and obtain the length
int length = Socket.Receive (arrRecvmsg);

// the socket arrays into the acquired character string of a human can understand
string strRevMsg = Encoding.UTF8.GetString (arrRecvmsg, 0 , length);

Msg = ( "Server:" + GetCurrentTime () + " IP:" + socket.RemoteEndPoint + ", the message:" + strRevMsg + "\ R & lt \ n-\ n-");
}
the catch (Exception EX)
{
msg = ( "The remote server has been disconnected" + "\ R & lt \ n-");
bREAK;
}
}
}

// get the current system time
Private GetCurrentTime String ()
{
String of TIMESTR = System.DateTime.Now.ToString ( "YYYY, MM-dd when the mm fraction day hh ss milliseconds seconds fff ");.
return of TIMESTR;
}

// send character information to the server process
public void ClientSendMsg (string SENDMSG)
{
content // converts a string input byte may identify the machine array
byte [] = arrClientSendMsg Encoding.UTF8.GetBytes (SENDMSG);
// call to the client socket array of bytes transmitted
socket.Send (arrClientSendMsg);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;

namespace TcpIpClint
{
class Program
{
static void Main(string[] args)
{
TcpIpClintEx tcpIpClintEx =new TcpIpClintEx("122.112.226.109");

while (true)
{
string strSend = Console.ReadLine();
if (strSend == "exit") break;
tcpIpClintEx.ClientSendMsg(strSend);
}
}
}
}
————————————————

原文链接:https://blog.csdn.net/u013628121/article/details/82968706

Guess you like

Origin www.cnblogs.com/zhengguangITelite/p/11388386.html