Guest User

Untitled

a guest
Jun 24th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 17.31 KB | None | 0 0
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading;
  8.  
  9. namespace Client
  10. {
  11.  
  12.     public class StateObject
  13.     {
  14.         // Client socket.
  15.         public Socket workSocket = null;
  16.         // Size of receive buffer.
  17.         public const int BufferSize = 256;
  18.         // Receive buffer.
  19.         public byte[] buffer = new byte[BufferSize];
  20.         // Received data string.
  21.         public StringBuilder sb = new StringBuilder();
  22.     }
  23.  
  24.     class ClientMain
  25.     {
  26.        
  27.         public static ManualResetEvent connectDone = new ManualResetEvent(false);
  28.         public static ManualResetEvent sendDone = new ManualResetEvent(false);
  29.         public static ManualResetEvent receiveDone = new ManualResetEvent(false);
  30.         Packet cPacket = new Packet();
  31.  
  32.         public static void Connect(EndPoint remoteEP, Socket client)
  33.         {
  34.             client.BeginConnect(remoteEP,
  35.                 new AsyncCallback(ConnectCallback), client);
  36.  
  37.             connectDone.WaitOne();
  38.         }
  39.         public static void ConnectCallback(IAsyncResult ar)
  40.         {
  41.             try
  42.             {
  43.                 // Retrieve the socket from the state object.
  44.                 Socket client = (Socket)ar.AsyncState;
  45.                 client = (Socket)ar.AsyncState;
  46.  
  47.                 // Complete the connection.
  48.                 client.EndConnect(ar);
  49.  
  50.                 // Signal that the connection has been made.
  51.                 connectDone.Set();
  52.             }
  53.             catch //(Exception e)
  54.             {
  55.                 Console.WriteLine("Server not found.");
  56.                 Console.ReadLine();
  57.             }
  58.         }
  59.         public static void Send(Socket client, byte[] data)
  60.         {
  61.  
  62.             // Begin sending the data to the remote device.
  63.             client.BeginSend(data, 0, data.Length, SocketFlags.None,
  64.             new AsyncCallback(SendCallback), client);
  65.         }
  66.         public static void SendCallback(IAsyncResult ar)
  67.         {
  68.             try
  69.             {
  70.                 Socket client = (Socket)ar.AsyncState;
  71.  
  72.                 ////////////////////////////////////////////////////////
  73.                 //SENDPACKETS()
  74.                 ////////////////////////////////////////////////////////
  75.  
  76.                 int bytesSent = client.EndSend(ar);
  77.  
  78.                 sendDone.Set();
  79.             }
  80.             catch (Exception e)
  81.             {
  82.                 Console.WriteLine(e.ToString());
  83.             }
  84.         }
  85.         public static void Receive(Socket client)
  86.         {
  87.             try
  88.             {
  89.                 // Create the state object.
  90.                 StateObject state = new StateObject();
  91.                 state.workSocket = client;
  92.  
  93.                 // Begin receiving the data from the remote device.
  94.                 client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  95.                     new AsyncCallback(ReceiveCallback), state);
  96.             }
  97.             catch (Exception e)
  98.             {
  99.                 Console.WriteLine(e.ToString());
  100.             }
  101.         }
  102.         public static void ReceiveCallback(IAsyncResult ar)
  103.         {
  104.             try
  105.             {
  106.                 StateObject state = (StateObject)ar.AsyncState;
  107.                 Socket client = state.workSocket;
  108.  
  109.                 int bytesRead = client.EndReceive(ar);
  110.  
  111.                 if (bytesRead > 0)
  112.                 {
  113.                     ////////////////////////////////////////////////////
  114.                     //ACCEPTPACKETS()
  115.                     ////////////////////////////////////////////////////
  116.  
  117.                     client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  118.                         new AsyncCallback(ReceiveCallback), state);
  119.                     state.sb.Clear();
  120.                 }
  121.                 else
  122.                 {
  123.                     receiveDone.Set();
  124.                 }
  125.             }
  126.             catch (Exception e)
  127.             {
  128.                 Console.WriteLine(e.ToString());
  129.             }
  130.         }
  131.  
  132.         public static string ConvertData()
  133.         {
  134.             return System.DateTime.Now.ToString();
  135.         }
  136.  
  137.         static void Main(string[] args)
  138.         {
  139.             IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);
  140.             Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  141.             ClientMain.Connect(localEndPoint, sock);
  142.  
  143.             ////////////////////////////////////////////////////////////////
  144.             // Send/Receive
  145.             ///////////////////////////////////////////////////////////////
  146.         }
  147.     }
  148. }
  149.  
  150.  
  151.  
  152. using System;
  153. using System.Net;
  154. using System.Net.Sockets;
  155. using System.Collections.Generic;
  156. using System.Linq;
  157. using System.Text;
  158. using System.Threading;
  159.  
  160. namespace Server
  161. {
  162.     // State object for reading client data asynchronously
  163.     public class StateObject
  164.     {
  165.         // Client  socket.
  166.         public Socket workSocket = null;
  167.         // Size of receive buffer.
  168.         public const int BufferSize = 1024;
  169.         // Receive buffer.
  170.         public byte[] buffer = new byte[BufferSize];
  171.         // Received data string.
  172.         public StringBuilder sb = new StringBuilder();
  173.     }
  174.  
  175.     public class StatesHandler
  176.     {
  177.         public List<StateObject> States = new List<StateObject>();
  178.         public int Counter = 0;
  179.     }
  180.  
  181.     public class AsynchronousSocketListener
  182.     {
  183.         public static Server.StatesHandler stateshandler = new StatesHandler();
  184.         // Thread signal.
  185.         public static ManualResetEvent allDone = new ManualResetEvent(false);
  186.  
  187.         public AsynchronousSocketListener()
  188.         {
  189.         }
  190.  
  191.         public static void StartListening()
  192.         {
  193.             // Data buffer for incoming data.
  194.             byte[] bytes = new Byte[1024];
  195.  
  196.  
  197.             // Establish the local endpoint for the socket.
  198.             // The DNS name of the computer
  199.             // running the listener is "host.contoso.com".
  200.             //IPHostEntry ipHostInfo = Dns.GetHostByName(Dns.GetHostName());
  201.             //IPAddress ipAddress = ipHostInfo.AddressList[0];;
  202.             IPAddress ipAddress = IPAddress.Loopback;
  203.             IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 3000);
  204.  
  205.             // Create a TCP/IP socket.
  206.             Socket listener = new Socket(AddressFamily.InterNetwork,
  207.             SocketType.Stream, ProtocolType.Tcp);
  208.  
  209.             // Bind the socket to the local endpoint and listen for incoming connections.
  210.             try
  211.             {
  212.                 listener.Bind(localEndPoint);
  213.                 listener.Listen(100);
  214.                 Console.WriteLine("Waiting for a connection @ " + ipAddress.ToString());
  215.  
  216.                 while (true)
  217.                 {
  218.                     // Set the event to nonsignaled state.
  219.                     allDone.Reset();
  220.  
  221.                     // Start an asynchronous socket to listen for connections.
  222.  
  223.                     listener.BeginAccept(
  224.                         new AsyncCallback(AcceptCallback),
  225.                         listener);
  226.  
  227.                     // Wait until a connection is made before continuing.
  228.                     allDone.WaitOne();
  229.                 }
  230.  
  231.             }
  232.             catch (Exception e)
  233.             {
  234.  
  235.                 Console.WriteLine(e.ToString());
  236.                 Console.WriteLine("\nPress ENTER to continue...");
  237.                 Console.Read();
  238.             }
  239.  
  240.             Console.WriteLine("\nPress ENTER to continue...");
  241.             Console.Read();
  242.  
  243.         }
  244.  
  245.         public static void AcceptCallback(IAsyncResult ar)
  246.         {
  247.             // Signal the main thread to continue.
  248.             allDone.Set();
  249.  
  250.             // Get the socket that handles the client request.
  251.             Socket listener = (Socket)ar.AsyncState;
  252.             Socket handler = listener.EndAccept(ar);
  253.  
  254.             // Create the state object.
  255.             StateObject state = new StateObject();
  256.  
  257.             //Store state instance in stateshandler
  258.             stateshandler.States.Add(state);
  259.             stateshandler.Counter+=1;
  260.  
  261.             state.workSocket = handler;
  262.             handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  263.                 new AsyncCallback(ReadCallback), state);
  264.             listener.BeginAccept(
  265.                         new AsyncCallback(AcceptCallback),
  266.                         listener);
  267.             Console.WriteLine("Connection accepted from: " + handler.RemoteEndPoint.ToString());
  268.         }
  269.  
  270.         public static void ReadCallback(IAsyncResult ar)
  271.         {
  272.             try
  273.             {
  274.                 String content = String.Empty;
  275.  
  276.                 // Retrieve the state object and the handler socket
  277.                 // from the asynchronous state object.
  278.                 StateObject state = (StateObject)ar.AsyncState;
  279.                 Socket handler = state.workSocket;
  280.  
  281.                 // Read data from the client socket.
  282.                 int bytesRead = handler.EndReceive(ar);
  283.  
  284.                 if (bytesRead > 0)
  285.                 {
  286.                     // There  might be more data, so store the data received so far.
  287.                     state.sb.Append(Encoding.ASCII.GetString(
  288.                         state.buffer, 0, bytesRead));
  289.  
  290.                     // Check for end-of-file tag. If it is not there, read
  291.                     // more data.
  292.                     content = state.sb.ToString();
  293.                     if (content != null)
  294.                     {
  295.                         // All the data has been read from the
  296.                         // client. Display it on the console.
  297.                         //Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
  298.                         //    content.Length, content);
  299.                         // Echo the data back to the client.
  300.                         Send(ar, content);
  301.                         state.sb.Clear();
  302.                     }
  303.                     else
  304.                     {
  305.                         // Not all data received. Get more.
  306.                         try
  307.                         {
  308.                             handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  309.                             new AsyncCallback(ReadCallback), state);
  310.                         }
  311.                         catch (Exception e)
  312.                         {
  313.                             Console.WriteLine(e);
  314.                             Console.Read();
  315.                         }
  316.                     }
  317.                 }
  318.             }
  319.             catch (Exception e)
  320.             {
  321.                 Console.WriteLine("A connection has been terminated.  Error:\n{0}", e);
  322.                 /*
  323.                  *
  324.                  * STATE OBJECTS HANDLER NEEDS TO STORE INDIVIDUAL STATE UNIQUE
  325.                  * IDENTIFIERS AS SOMETHING OTHER THAN A SEQUENCE OF INTEGERS
  326.                  * AS WE NEED TO REMOVE FROM THE LIST BY THAT UNIQUE ID
  327.                  *
  328.                  *
  329.                  *
  330.                  * ARGHHHHH
  331.                  */
  332.             }
  333.  
  334.         }
  335.  
  336.         private static void Send(IAsyncResult ar, String data)
  337.         {
  338.  
  339.             for (int i = 0; i < stateshandler.Counter; i++)
  340.             {
  341.                 StateObject state = stateshandler.States[i];
  342.                 Socket handler = state.workSocket;
  343.                 // Convert the string data to byte data using ASCII encoding.
  344.                 byte[] byteData = Encoding.ASCII.GetBytes(data);
  345.  
  346.                 if (state != (StateObject)ar.AsyncState)
  347.                 {
  348.                     // Begin sending the data to the remote device.
  349.                     handler.BeginSend(byteData, 0, byteData.Length, 0,
  350.                         new AsyncCallback(SendCallback), state);
  351.                 }
  352.             }
  353.  
  354.         }
  355.  
  356.         private static void SendCallback(IAsyncResult ar)
  357.         {
  358.             try
  359.             {
  360.                 // Retrieve the socket from the state object.
  361.                 StateObject state = (StateObject)ar.AsyncState;
  362.                 Socket handler = state.workSocket;
  363.  
  364.                 // Complete sending the data to the remote device.
  365.                 int bytesSent = handler.EndSend(ar);
  366.                 //Console.WriteLine("Sent {0} bytes to client.", bytesSent);
  367.  
  368.                 handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  369.                     new AsyncCallback(ReadCallback), state);
  370.             }
  371.             catch (Exception e)
  372.             {
  373.                 Console.WriteLine(e.ToString());
  374.                 Console.WriteLine("\nPress ENTER to continue...");
  375.                 Console.Read();
  376.             }
  377.         }
  378.  
  379.  
  380.         public static int Main(String[] args)
  381.         {
  382.             try
  383.             {
  384.                 StartListening();
  385.             }
  386.             catch (Exception e)
  387.             {
  388.                 Console.WriteLine(e.ToString());
  389.                 Console.WriteLine("\nPress ENTER to continue...");
  390.                 Console.Read();
  391.             }
  392.             Console.Read();
  393.             return 0;
  394.         }
  395.     }
  396. }
  397.  
  398.  
  399.  
  400. using System;
  401. using System.Collections.Generic;
  402. using System.Linq;
  403. using Microsoft.Xna.Framework;
  404. using Microsoft.Xna.Framework.Audio;
  405. using Microsoft.Xna.Framework.Content;
  406. using Microsoft.Xna.Framework.GamerServices;
  407. using Microsoft.Xna.Framework.Graphics;
  408. using Microsoft.Xna.Framework.Input;
  409. using Microsoft.Xna.Framework.Media;
  410. using System.Net;
  411. using System.Net.Sockets;
  412. using System.Text;
  413. using System.Threading;
  414.  
  415. namespace Networked_Sprite_Animation
  416. {
  417.     /// <summary>
  418.     /// This is the main type for your game
  419.     /// </summary>
  420.     public class Game : Microsoft.Xna.Framework.Game
  421.     {
  422.         Sprite sprite;
  423.         GraphicsDeviceManager graphics;
  424.         SpriteBatch spriteBatch;
  425.         IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);
  426.         Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  427.         Transmit data = new Transmit();
  428.         string buffer;
  429.  
  430.  
  431.        
  432.  
  433.         public Game()
  434.         {
  435.             graphics = new GraphicsDeviceManager(this);
  436.             Content.RootDirectory = "Content";
  437.         }
  438.  
  439.         /// <summary>
  440.         /// Allows the game to perform any initialization it needs to before starting to run.
  441.         /// This is where it can query for any required services and load any non-graphic
  442.         /// related content.  Calling base.Initialize will enumerate through any components
  443.         /// and initialize them as well.
  444.         /// </summary>
  445.         protected override void Initialize()
  446.         {
  447.             Networked_Sprite_Animation.Client.Connect(localEndPoint, sock);
  448.             base.Initialize();
  449.         }
  450.  
  451.         /// <summary>
  452.         /// LoadContent will be called once per game and is the place to load
  453.         /// all of your content.
  454.         /// </summary>
  455.         protected override void LoadContent()
  456.         {
  457.             spriteBatch = new SpriteBatch(GraphicsDevice);
  458.  
  459.             sprite = new Sprite(Content.Load<Texture2D>("SpriteSheet"), 1, 32, 48);
  460.  
  461.             sprite.Position = new Vector2(400, 300);
  462.         }
  463.  
  464.         /// <summary>
  465.         /// UnloadContent will be called once per game and is the place to unload
  466.         /// all content.
  467.         /// </summary>
  468.         protected override void UnloadContent()
  469.         {
  470.             // TODO: Unload any non ContentManager content here
  471.         }
  472.  
  473.         /// <summary>
  474.         /// Allows the game to run logic such as updating the world,
  475.         /// checking for collisions, gathering input, and playing audio.
  476.         /// </summary>
  477.         /// <param name="gameTime">Provides a snapshot of timing values.</param>
  478.         protected override void Update(GameTime gameTime)
  479.         {
  480.             sprite.HandleSpriteMovement(gameTime);
  481.  
  482.  
  483.             // Allows the game to exit
  484.             if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
  485.                 this.Exit();
  486.  
  487.             buffer = sprite.Texture.ToString() + sprite.SourceRect.ToString() + sprite.Position.ToString() + sprite.Origin.ToString();
  488.             for (int i = 0; i < 3; i++)
  489.             {
  490.                 Client.Send(sock, buffer);
  491.             }
  492.  
  493.             base.Update(gameTime);
  494.         }
  495.  
  496.         /// <summary>
  497.         /// This is called when the game should draw itself.
  498.         /// </summary>
  499.         /// <param name="gameTime">Provides a snapshot of timing values.</param>
  500.         protected override void Draw(GameTime gameTime)
  501.         {
  502.             GraphicsDevice.Clear(Color.DarkOliveGreen);
  503.  
  504.             spriteBatch.Begin();
  505.             spriteBatch.Draw(sprite.Texture, sprite.Position, sprite.SourceRect, Color.White, 0f, sprite.Origin, 1.0f, SpriteEffects.None, 0);
  506.             spriteBatch.End();
  507.  
  508.             base.Draw(gameTime);
  509.         }
  510.     }
  511. }
  512.  
  513.  
  514.  
  515. using System;
  516. using System.Collections.Generic;
  517. using System.Linq;
  518. using System.Text;
  519.  
  520. namespace Client
  521. {
  522.     public class Packet
  523.     {
  524.         byte[] bData;
  525.  
  526.         public Packet()
  527.         {
  528.  
  529.         }
  530.  
  531.         public Packet(int data)
  532.         {
  533.             bData = Encoding.ASCII.GetBytes(data.ToString());
  534.         }
  535.  
  536.         public byte[] getData()
  537.         {
  538.             return bData;
  539.         }
  540.     }
  541. }
Add Comment
Please, Sign In to add comment