Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Net.NetworkInformation;
- using System.Net;
- using System.Threading;
- using System.Net.Sockets;
- using MySql.Data.MySqlClient;
- namespace ConsoleApplication3
- {
- class Program
- {
- class ThreadedServer
- {
- private Socket _serverSocket;
- private int _port;
- private string db_connect = "Database=test_login;Data Source=localhost;User Id=server;Password=qwerasdf";
- private MySqlConnection myConnection;
- private int id;
- public ThreadedServer(int port) { _port = port; }
- public void Start()
- {
- myConnection = new MySqlConnection(db_connect);
- SetupServerSocket();
- for (int i = 0; i < 10; i++)
- _serverSocket.BeginAccept(new
- AsyncCallback(AcceptCallback), _serverSocket);
- }
- private class ConnectionInfo
- {
- public Socket Socket;
- public byte[] Buffer;
- public int user_id;
- public int char_id;
- public int id;
- public string nick;
- public float x;
- public float y;
- public float z;
- }
- private List<ConnectionInfo> _connections = new List<ConnectionInfo>();
- private void SetupServerSocket()
- {
- // Получаем информацию о локальном компьютере
- /* IPHostEntry localMachineInfo =
- Dns.GetHostEntry(Dns.GetHostName());*/
- IPEndPoint myEndpoint = new IPEndPoint(IPAddress.Any, _port);
- // Создаем сокет, привязываем его к адресу
- // и начинаем прослушивание
- _serverSocket = new Socket(
- myEndpoint.Address.AddressFamily,
- SocketType.Stream, ProtocolType.Tcp);
- _serverSocket.Bind(myEndpoint);
- _serverSocket.Listen((int)
- SocketOptionName.MaxConnections);
- }
- private void AcceptCallback(IAsyncResult result)
- {
- ConnectionInfo connection = new ConnectionInfo();
- try
- {
- // Завершение операции Accept
- Console.WriteLine("Подключился чел");
- Socket s = (Socket)result.AsyncState;
- connection.Socket = s.EndAccept(result);
- connection.Buffer = new byte[256];
- lock (_connections) _connections.Add(connection);
- // Начало операции Receive и новой операции Accept
- connection.Socket.BeginReceive(connection.Buffer,
- 0, connection.Buffer.Length, SocketFlags.None,
- new AsyncCallback(ReceiveCallback),
- connection);
- _serverSocket.BeginAccept(new AsyncCallback(
- AcceptCallback), result.AsyncState);
- }
- catch (SocketException exc)
- {
- CloseConnection(connection);
- Console.WriteLine("Socket exception: " +
- exc.SocketErrorCode);
- }
- catch (Exception exc)
- {
- CloseConnection(connection);
- Console.WriteLine("Exception: " + exc);
- }
- }
- private void ReceiveCallback(IAsyncResult result)
- {
- ConnectionInfo connection =
- (ConnectionInfo)result.AsyncState;
- try
- {
- int bytesRead =
- connection.Socket.EndReceive(result);
- if (0 != bytesRead)
- {
- lock (_connections)
- {
- string req = Encoding.UTF8.GetString(connection.Buffer, 0, 1);
- string all_req = Encoding.UTF8.GetString(connection.Buffer, 0, bytesRead);
- Console.WriteLine("comm = "+req);
- switch (req)
- {
- case "%":
- string[] split = all_req.Split(new Char[] { '%', '&', '%' });
- id = Lreq_To_bd(split[1], split[2]); Console.WriteLine("id = "+id);
- if (id != 0)
- {
- connection.id = id;
- byte[] b = BitConverter.GetBytes(id);
- Console.WriteLine("id = " + id);
- connection.Socket.Send(b, b.Length, SocketFlags.None);
- Console.WriteLine("Sended. Length = " + b.Length);
- }
- else
- {
- byte[] b = BitConverter.GetBytes(id);
- //Console.WriteLine("id = " + id);
- connection.Socket.Send(b, b.Length, SocketFlags.None);
- Console.WriteLine("Sended. Length = " + b.Length);
- }
- break;
- case "c":
- int id_for_chars = BitConverter.ToInt32(connection.Buffer, 1);
- Console.WriteLine(">> Запрос на список персов:\t" + Encoding.UTF8.GetString(connection.Buffer,0,1)+" "+id_for_chars);
- byte[] bf = new byte[256];
- bf = GetChars(id_for_chars);
- connection.Socket.Send(bf, bf.Length, SocketFlags.None);
- Console.WriteLine("Список персов послан:\t" + Encoding.UTF8.GetString(bf));
- break;
- case "h":
- int id_for_new = BitConverter.ToInt32(connection.Buffer, 1);
- int count = BitConverter.ToInt32(connection.Buffer, 5);
- Console.WriteLine("bytes read = " + bytesRead);
- string nick_for_new = Encoding.UTF8.GetString(connection.Buffer, 9, count);
- byte[] bn = SetNewNick(id_for_new, nick_for_new);
- connection.Socket.Send(bn, bn.Length, SocketFlags.None);
- Console.WriteLine("Ошибка послана: "+Encoding.UTF8.GetString(bn,0,1)+" "+BitConverter.ToInt32(bn,1));
- break;
- case "d":
- int id_for_del = BitConverter.ToInt32(connection.Buffer, 1);
- int count_del = BitConverter.ToInt32(connection.Buffer, 5);
- string nick_for_del = Encoding.UTF8.GetString(connection.Buffer, 9, count_del);
- DeleteChar(nick_for_del,id_for_del);
- break;
- case "g":
- string nick_for_spawn = Encoding.UTF8.GetString(connection.Buffer, 5, BitConverter.ToInt32(connection.Buffer, 1));
- byte[] bg = new byte[256];
- bg = GetSpawn_and_CharID(nick_for_spawn);
- connection.Socket.Send(bg, bg.Length, SocketFlags.None);
- Console.WriteLine("Точки спавна отправленны");
- break;
- case "n":
- connection.user_id = BitConverter.ToInt32(connection.Buffer, 1);
- connection.char_id = BitConverter.ToInt32(connection.Buffer, 5);
- connection.x = BitConverter.ToInt32(connection.Buffer, 9);
- connection.y = BitConverter.ToInt32(connection.Buffer, 13);
- connection.z = BitConverter.ToInt32(connection.Buffer, 17);
- connection.nick = Encoding.UTF8.GetString(connection.Buffer, 25, BitConverter.ToInt32(connection.Buffer, 21));
- foreach (ConnectionInfo conn in _connections)
- {
- if (conn != connection)
- {
- conn.Socket.Send(connection.Buffer,connection.Buffer.Length, SocketFlags.None);
- Console.WriteLine("new " + Encoding.UTF8.GetString(connection.Buffer, 0, connection.Buffer.Length));
- }
- }
- break;
- default:
- foreach (ConnectionInfo conn in _connections)
- {
- if (conn != connection)
- conn.Socket.Send(connection.Buffer, connection.Buffer.Length, SocketFlags.None);
- }
- break;
- }
- }
- connection.Socket.BeginReceive(
- connection.Buffer, 0,
- connection.Buffer.Length, SocketFlags.None,
- new AsyncCallback(ReceiveCallback),
- connection);
- }
- else CloseConnection(connection);
- }
- catch (SocketException exc)
- {
- CloseConnection(connection);
- Console.WriteLine("Socket exception: " +
- exc.SocketErrorCode);
- }
- catch (Exception exc)
- {
- CloseConnection(connection);
- Console.WriteLine("Exception: " + exc);
- }
- }
- private void CloseConnection(ConnectionInfo ci)
- {
- ci.Socket.Close();
- lock (_connections) _connections.Remove(ci);
- }
- public int Lreq_To_bd(string l, string p)
- {
- string request = "call GetId('"+l+"','"+p+"')";
- MySqlCommand myCommand = new MySqlCommand(request, myConnection);
- int value = 0;
- try
- {
- myConnection.Open();
- value = int.Parse(myCommand.ExecuteScalar().ToString());
- myConnection.Close();
- Console.WriteLine("value = " + value);
- Console.WriteLine("done sending req to bd. Value = " + value);
- }
- catch (Exception e) {
- myConnection.Close();
- Console.WriteLine("299 строка: "+e.Message); }
- return value;
- }
- public byte[] GetSpawn_and_CharID(string nick)
- {
- byte[] buff = new byte[256];
- int point = 4;
- string query = "CALL GetSpawn_and_CharID('" + nick + "')";
- MySqlCommand myCommand = new MySqlCommand(query, myConnection);
- MySqlDataReader MyDataReader;
- myConnection.Open();
- MyDataReader = myCommand.ExecuteReader();
- MyDataReader.Read();
- for (int i = 0; i < 3; i++)
- {
- BitConverter.GetBytes(MyDataReader.GetFloat(i)).CopyTo(buff,point);
- point += 4;
- }
- BitConverter.GetBytes(MyDataReader.GetInt32(3)).CopyTo(buff, point);
- Encoding.UTF8.GetBytes("g").CopyTo(buff, 0);
- return buff;
- }
- byte[] SetNewNick(int id, string nick)
- {
- byte[] b = new byte[256];
- Console.WriteLine("id for new = S" + id+"E nick for new = S"+nick+"E");
- string str = "CALL SetNick('" + nick + "'," + id + ")";
- Console.WriteLine("запрос - " + str);
- MySqlCommand myCommand = new MySqlCommand(str, myConnection);
- try
- {
- myConnection.Open();
- myCommand.ExecuteScalar();
- myConnection.Close();
- Encoding.UTF8.GetBytes("h").CopyTo(b, 0);
- BitConverter.GetBytes(1).CopyTo(b, 1);
- return b;
- }
- catch
- {
- byte[] bb = new byte[256];
- Encoding.UTF8.GetBytes("h").CopyTo(bb, 0);
- BitConverter.GetBytes(-1).CopyTo(bb, 1);
- return bb;
- }
- }
- void DeleteChar(string nick,int id)
- {
- string str = "CALL DelNick(" + id + ",'" + nick + "')";
- MySqlCommand myCommand = new MySqlCommand(str, myConnection);
- myConnection.Open();
- myCommand.ExecuteScalar();
- myConnection.Close();
- }
- byte[] GetChars(int id)
- {
- byte[] bf = new byte[256];
- int num;
- string str = "CALL get_num("+id+")";
- MySqlCommand myCommand = new MySqlCommand(str, myConnection);
- myConnection.Open();
- num = Convert.ToInt32(myCommand.ExecuteScalar().ToString());
- myConnection.Close();
- Console.WriteLine("num = "+num);
- if (num == 0)
- {
- return bf = Encoding.UTF8.GetBytes("0");
- }
- else
- {
- bf = GetNick(id, num);
- BitConverter.GetBytes(num).CopyTo(bf, 1);
- }
- // byte[] b = Encoding.UTF8.GetBytes("c");
- //b.CopyTo(bf, 0);
- //BitConverter.GetBytes(num).CopyTo(bf, 1);
- return bf;
- }
- byte[] GetNick(int id, int i)
- {
- byte[] bf = new byte[256];
- Console.WriteLine("connected");
- int point = 20;
- string query = "CALL get_chars("+id+")";
- MySqlCommand myCommand = new MySqlCommand(query, myConnection);
- MySqlDataReader MyDataReader;
- myConnection.Open();
- MyDataReader = myCommand.ExecuteReader();
- while(MyDataReader.Read())
- {
- string s = MyDataReader.GetString(0);
- Console.WriteLine("names = "+s);
- Encoding.UTF8.GetBytes(s).CopyTo(bf, point);
- point += 20;
- }
- myConnection.Close();
- byte[] bb = Encoding.UTF8.GetBytes("c");
- bb.CopyTo(bf, 0);
- return bf;
- }
- }
- static void Main(string[] args)
- {
- ThreadedServer ts = new ThreadedServer(9390);
- ts.Start();
- Console.ReadLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement