C # UDP hole trial

xiaoxiao2021-03-06  14

I have limited technology, and I may have a bad code ~~ I can't help but I can't help. . . I hope that I can forgive me for this rookie, I have an advocacy to leave a message, but please don't hurt my young heart.

Public code:

///

/// User class /// public class user {/// /// User Name /// private string name = "";

///

/// user's network address /// private endpoint location = null;

///

/// username property /// public string name {get {return name;}}

///

/// User Address Properties /// public endpoint location {get {return location;}}

///

/// Returns a user instance //// /// Username /// user address public user (string _name, endpoint _location) {name = _name; location = _location;}}}

Client program code:

Using system.net; using system.Text; using system.threading; using system.collections;

A summary description of Namespace Client {///

/// Class1. /// class clientApp {#Region parameters ...

/ * Client to server * / const string login = "11"; // client login const string logout = "12"; // Client offline const string getList = "13"; // Request User List Const String P2PCON = "14"; // Request P2P connection

/ * The server to the client * / const string nonuser = "21"; // requests the connected user does not exist const string rename = "22"; // Log in user name already existing const string userlist = "23"; // Online User list const string makhold = "24"; // UDP hole command const string loginok = "25"; // Login success const string servcls = "26"; // server closing const string msgend = "27"; //// End of the message

/ * Client to client * / const string p2pmsg = "31"; // client message const string Holdmg = "32"; // udp hole message const string recmsg = "33"; // message answer const string Pingmg = "34"; // ping client / * network parameter * / const Int maxTry = 5; // Number of retry times

/ * Client command line * / const string getUsers = "getu"; // Get online user list const string sendmsg = "send"; // Send message to a client const string exit = "exit"; // Exit Program const string ping = "ping"; const string users = "user"; // Print online user const string help = "help"; // Help

/ * Program variables * / static bool more = true; static bool ok = true; static string Username = ""; // username static ArrayList users = new ArrayList (); static Socket sock = new Socket (AddressFamily.InterNetwork, SocketType .Dgram, protocoltype.udp); Static IpendPoint Serverep = New IpendPoint (iPaddress.Parse ("222.76.56.239"), 8888); Static Thread Listenr = New Thread (New ThreadStart (Listen);

#ndregion

#REGION method ...

Static Private Void Listen () {while (true) {int RECV = 0; // Received Message bytes

Byte [] data = new byte [1024]; // message buffer

IpendPoint Sender = new iPadpoint (iPaddress.Any, 0); endpoint remote = (endpoint) sender; // message source remote address

Recv = sock.receiveFrom (data, ref remote); string head = encoding.unicode.getstring (data, 0, 4); // Get the message head two bytes of tag Switch (hEAD) {Case Recmsg: OK = true ;

Case UserList: getUserList (Data, RECV); Break;

Case msgend: more = false; Break;

Case servcls: console.writeline ("/ n server is closed! / n"); console.write ("# command:"); break;

Case Makhold: String Recever = Encoding.Unicode.getstring (data, 4, 20); int index = finduser (receser);

IF (index! = -1) {sock.sendto (Encoding.unicode.getBytes (Holdmg), ((USER) Users [index]). Location);

Break;

Case p2pmsg: console.writeline ("/ N received message from" encoding.unicode.getstring (DATA, 4, 20) ":" Encoding.Unicode.getstring (Data, 24, RECV - 24);

Sock.sendto (Encoding.unicode.getbytes (Recmsg), Remote;

Console.write ("/ n # command:"); Break;

Case Holdmg: Break;

Case pingmg: Break;}}}

/ * User Login * / Static String UserLogin () {iependpoint sender = new ipndpoint (ipaddress.any, 0); Endpoint Remote = (endpoint) sender; // message source remote address

Console.write ("Please enter a username:");

String Username = console.readline ();

Byte [] temp = encoding.unicode.getbytes (username);

IF (Temp.length> 20) {Console.WriteLine ("User Name cannot exceed 20 bytes! / n"); return ";} username = username.padright (10, '); byte [] data = Encoding.unicode.getBytes (login username.toupper ());

Sock.sendto (DATA, SERVEREP);

// Todo: Remember to add timeout processing int RECV = Sock.Receive (DATA);

IF (Encoding.unicode.getstring (DATA, 0, RECV) == Loginok) {Console.Writeline ("Landing Success! / N"); showhelp (); console.writeline ();

Return UserName;} else {console.writeline ("Landing failed, username already existing! / n"); return "";}}

/ * Send message * / static private bool sendmsg (String name, string msg) {bool result = false

Name = Name.padright (10, '');

INT INDEX = Finduser (Name);

IF (index! = -1) {byte [] Toserv = Encoding.unicode.getBytes (P2PCON NAME Username); Byte [] TOCLIENT = Encoding.Unicode.getbytes (P2PMSG UserName MSG); OK = FALSE;

For (int i = 0; i

SOCK.SENDTO (TOCLIENT, ((USER) Users [index]). Location);

Thread.sleep (1000);

For (int i = 0; i

Sock.sendto (TOSERV, SERVEREP);

Thread.sleep (1000);

Sock.sendto (Toclient, ((user) Users [index]). location);

If (! ok) {console.writeline ("message delivery failed ./N");} else {console.writeLine ("message sends success ./n");}} else {console.writeline ("The user does not exist. / N ");

Return Result;}

/ * Get User List * / Static Private Void getUserList (Byte [] Data, Int Recv) {string userdata = encoding.unicate.getstring (data, 4, recv-4); string username = userData.substring (0, 10) ;

IF (fileuser == -1) {int portindex = userdata.indexof (':');

String address = userdata.substring (10, userdata.length - (userData.Length - PortIndex) - 10);

IpendPoint UseRep = New IpendPoint (iPaddress.Parse (Address), INT.PARS (UserData.Substring (PortIndex 1)));

Endpoint location = (endpoint) USEREP;

Users.add (New User (User (User (User ");}}

/ * Print Online User List * / Static Private Void Printfusers () {if (users.count! = 0) {Console.WriteLine ("Online User:");

For (int i = 0; i

/ * Find user * / static private int founduser (string _name) {int result = -1;

For (int I = 0; i

Break;}}

Return Result;}

Static void waitunerlist () {byte [] data = encoding.uitode.getbytes (getList);

Sock.sendto (DATA, SERVEREP);

More = True;

For (int I = 0; i

Thread.sleep (1000);

IF (more) {console.writeline ("Get User List Fails! Server Timeout! / N");} else {printfusers ();}}

Static void showhelp () {console.writeLine ("/ t / t -------------------------------") Console.Writeline ("/ T / T | Getu Get Online User List |"); console.writeline ("/ t / t | send message to a client |"); console.writeline ("/ t / T | User prints online users | "); console.writeline (" / t / t | exit exit program | "); console.writeline (" / t / t -------------- ------------------- ");

#ndregion

///

/// The primary entry point of the application. /// [stathread] static void main (String [] args) {bool loop = true;

// Byte [] data = new byte [1024];

While (LOOP) {Console.Write ("Please enter server IP:"); string ip = console.readline ();

Try {serverep = new ipndpoint (ipaddress.parse (ip), 8888); loop = false;} catch {console.write ("Please enter IP is incorrect ./n"); loop = true;}}

Loop = true;

/ * User login * / while (username == ") {username = userlogin ();

Listenthr.start ();

While (LOOP) {Console.write ("# command:");

String Input = console.readline ();

IF (Input.Length <4) {console.writeline ("'" input "" is not a valid command! / n "); Continue;} switch (INPUT.SUBSTRING (0, 4) .tolower () ) {Case getUsers: if (Input.length == 4) {WaitUserList ();} else {console.writeLine ("'" input "" "is not a valid command! / N");}

Break;

Case users: if (Input.Length == 4) {printfusers ();} else {console.writeline ("'" input "" is not a valid command! / n ");} Break;

Case sendmsg: if (Input.Length> 5 && Input [4] == ') {INT NINDEX = INPUT.INDEXOF (' ', 5); if (Nindex <0 || NINDEX == Input.length-1) {Console.WriteLine ("Send command format should be as follows:"); console.writeline ("Send [User Name] [Message Content] / N"); Break;}

String name = INPUT.SUBSTRING (5, NINDEX-5) .toupper (); string msg = input.substring (NINDEX 1);

Sendmsg (Name, MSG);} else {console.writeline ("'" input "" "is not a valid command! / N");

Break;

Case EXIT: IF (Input.Length == 4) {loop = false;

Byte [] temp = encoding.unicode.getbytes (username); byte [] data = encoding.unicode.getBytes (logout temp.length.tostring ("0 #") username.toupper ());

Listenthr.abort ();

Sock.sendto (DATA, SERVEREP); sock.close ();} else {console.writeLine ("'" input "" is not a valid command! / n ");} Break;

Case ping: IF (Input.length> 5 && Input [4] == ') {console.writeline ("command is completed ./n");} else {console.writeline ("'" input "" " "Not a valid command! / N");

Break;

Case help: showhelp (); break; default: console.writeline ("'" input "'" "is not a valid command! / n"); Break;}}}}

Server-end program code:

Using system.collections; using system.net; using system.text; using system.Text;

Summary description of Namespace Server {///

/// class1. /// Class ServerApp {#Region parameters ...

/ * Client to server * / const string login = "11"; // client login const string logout = "12"; // Client offline const string getList = "13"; // Request User List Const String P2PCON = "14"; // Request P2P connection

/ * The server to the client * / const string nonuser = "21"; // requests the connected user does not exist const string rename = "22"; // Log in user name already existing const string userlist = "23"; // Online User list const string makhold = "24"; // UDP hole command const string loginok = "25"; // Login success const string servcls = "26"; // server closing const string msgend = "27"; //// End of the message

/ * Server command line * / const string exit = "exit"; // Exit the program const string users = "user"; // Print online users

/ * Program variables * / static ArrayList users = new ArrayList (); // User List static Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); static IPEndPoint ipep = new IPEndPoint (IPAddress.Any, 8888); Static Thread Listenthr = New Threadstart (Listen)); # endregion

#Region method ... static private void listen () {while (true) {int RECV = 0; // receive the number of message bytes

Byte [] data = new byte [1024]; // message buffer

IpendPoint Sender = new iPadpoint (iPaddress.Any, 0); endpoint remote = (endpoint) sender; // message source remote address

RECV = Sock.ReceiveFrom (data, ref remote);

String head = encoding.unicode.getstring (data, 0, 4); // Get two bytes of the message header

Switch (Head) {Case Login: UserLogin (Data, Remote); Break;

Case Logout: UserLogout (data); Break;

Case getList: getUserList (transote); Break;

Case P2PCON: Peerconnect (Data, Remote); Break;}}}

/ * Find user * / static private int founduser (string _name) {int result = -1;

For (int I = 0; i

Break;}}

Return Result;}

/ * User Login * / Static Private Void UserLogin (Byte [] data, endpoint _remote) {bool error = false;

/ * Newly registered users * / user newuser = new user (Encoding.Unicode.getstring (data, 4, 20), _remote);

/ * Judging whether the user recommends * / error = (Finduser (NewUser.Name)! = -1);

IF (! error) {users.add (newuser);

Console.writeline ("/ N users" newuser.name "login, address:" newuser.location.toString () "/ n"); console.write ("# command:");

Sock.sendto (encoding.unicode.getBytes (loginok), _Remote); for (INT i = 0; i

IF (index! = -1) {users.removeat (index); console.writeline ("/ n user" username "exit ./N"); console.write ("# command:");}}

/ * Get online users list * / static private remote, {for (int i = 0; i

Sock.sendto (UserData, Remote);

Sock.sendto (Encoding.Unicode.getbytes (Msgend), Remote;

/ * Command Over-end connection * / static private void peerconnect (byte [] data, endpoint remote) {string received (data, 4, 20); string sender = encoding. commnicode.getstring (Data) 20, 20);

Byte [] msg = encoding.unicode.getbytes (Makhold Sender);

INT INDEX = Finduser (Recever);

IF (index! = -1) {sock.sendto (MSG, ((user) Users [index]);} else {sock.sendto (eNCoding.unicode.getBytes (nonuser), remote);}}

/ * Print Online User List * / Static Private Void Printfusers () {if (users.count! = 0) {Console.WriteLine ("Online User:");

For (int i = 0; i

///

/// The primary entry point of the application. /// [stathread] static void main (String [] args) {bool loop = true;

Sock.bind (IPEP);

Listenthr.start ();

Console.writeline ("Server has started ..... / n");

While (LOOP) {Console.write ("# command:");

String Input = console.readline ();

IF (Input.Length <4) {console.writeline ("'" input "" "is not a valid command! / n"); Continue;}

Switch (INPUT.SUBSTRING (0, 4) .tolower ()) {CASE USERS: IF (INPUT.LENGTH == 4) {printfusers ();} else {console.writeline ("'" input "" " Not a valid command! / N ");

Break;

Case EXIT: Listenthr.abort (); Byte [] Data = Encoding.unicode.getbytes (servcls);

For (int i = 0; i

Sock.close (); loop = false;

Break;

Default: console.writeline ("'" input "" is not a valid command! / n "); Break;}}}}

Explain the UDP hole with an empty, what is going on, the code is very chaotic, please forgive me!

I didn't succeed many times, I don't know where the code is wrong ~~~ I have time to check.

转载请注明原文地址:https://www.9cbs.com/read-46912.html

New Post(0)