Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- namespace Client
- {
- public class StateObject
- {
- // Client socket.
- public Socket workSocket = null;
- // Size of receive buffer.
- public const int BufferSize = 256;
- // Receive buffer.
- public byte[] buffer = new byte[BufferSize];
- // Received data string.
- public StringBuilder sb = new StringBuilder();
- }
- class ClientMain
- {
- public static ManualResetEvent connectDone = new ManualResetEvent(false);
- public static ManualResetEvent sendDone = new ManualResetEvent(false);
- public static ManualResetEvent receiveDone = new ManualResetEvent(false);
- Packet cPacket = new Packet();
- public static void Connect(EndPoint remoteEP, Socket client)
- {
- client.BeginConnect(remoteEP,
- new AsyncCallback(ConnectCallback), client);
- connectDone.WaitOne();
- }
- public static void ConnectCallback(IAsyncResult ar)
- {
- try
- {
- // Retrieve the socket from the state object.
- Socket client = (Socket)ar.AsyncState;
- client = (Socket)ar.AsyncState;
- // Complete the connection.
- client.EndConnect(ar);
- // Signal that the connection has been made.
- connectDone.Set();
- }
- catch //(Exception e)
- {
- Console.WriteLine("Server not found.");
- Console.ReadLine();
- }
- }
- public static void Send(Socket client, byte[] data)
- {
- // Begin sending the data to the remote device.
- client.BeginSend(data, 0, data.Length, SocketFlags.None,
- new AsyncCallback(SendCallback), client);
- }
- public static void SendCallback(IAsyncResult ar)
- {
- try
- {
- Socket client = (Socket)ar.AsyncState;
- ////////////////////////////////////////////////////////
- //SENDPACKETS()
- ////////////////////////////////////////////////////////
- int bytesSent = client.EndSend(ar);
- sendDone.Set();
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- }
- public static void Receive(Socket client)
- {
- try
- {
- // Create the state object.
- StateObject state = new StateObject();
- state.workSocket = client;
- // Begin receiving the data from the remote device.
- client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
- new AsyncCallback(ReceiveCallback), state);
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- }
- public static void ReceiveCallback(IAsyncResult ar)
- {
- try
- {
- StateObject state = (StateObject)ar.AsyncState;
- Socket client = state.workSocket;
- int bytesRead = client.EndReceive(ar);
- if (bytesRead > 0)
- {
- ////////////////////////////////////////////////////
- //ACCEPTPACKETS()
- ////////////////////////////////////////////////////
- client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
- new AsyncCallback(ReceiveCallback), state);
- state.sb.Clear();
- }
- else
- {
- receiveDone.Set();
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- }
- public static string ConvertData()
- {
- return System.DateTime.Now.ToString();
- }
- static void Main(string[] args)
- {
- IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);
- Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- ClientMain.Connect(localEndPoint, sock);
- ////////////////////////////////////////////////////////////////
- // Send/Receive
- ///////////////////////////////////////////////////////////////
- }
- }
- }
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- namespace Server
- {
- // State object for reading client data asynchronously
- public class StateObject
- {
- // Client socket.
- public Socket workSocket = null;
- // Size of receive buffer.
- public const int BufferSize = 1024;
- // Receive buffer.
- public byte[] buffer = new byte[BufferSize];
- // Received data string.
- public StringBuilder sb = new StringBuilder();
- }
- public class StatesHandler
- {
- public List<StateObject> States = new List<StateObject>();
- public int Counter = 0;
- }
- public class AsynchronousSocketListener
- {
- public static Server.StatesHandler stateshandler = new StatesHandler();
- // Thread signal.
- public static ManualResetEvent allDone = new ManualResetEvent(false);
- public AsynchronousSocketListener()
- {
- }
- public static void StartListening()
- {
- // Data buffer for incoming data.
- byte[] bytes = new Byte[1024];
- // Establish the local endpoint for the socket.
- // The DNS name of the computer
- // running the listener is "host.contoso.com".
- //IPHostEntry ipHostInfo = Dns.GetHostByName(Dns.GetHostName());
- //IPAddress ipAddress = ipHostInfo.AddressList[0];;
- IPAddress ipAddress = IPAddress.Loopback;
- IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 3000);
- // Create a TCP/IP socket.
- Socket listener = new Socket(AddressFamily.InterNetwork,
- SocketType.Stream, ProtocolType.Tcp);
- // Bind the socket to the local endpoint and listen for incoming connections.
- try
- {
- listener.Bind(localEndPoint);
- listener.Listen(100);
- Console.WriteLine("Waiting for a connection @ " + ipAddress.ToString());
- while (true)
- {
- // Set the event to nonsignaled state.
- allDone.Reset();
- // Start an asynchronous socket to listen for connections.
- listener.BeginAccept(
- new AsyncCallback(AcceptCallback),
- listener);
- // Wait until a connection is made before continuing.
- allDone.WaitOne();
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- Console.WriteLine("\nPress ENTER to continue...");
- Console.Read();
- }
- Console.WriteLine("\nPress ENTER to continue...");
- Console.Read();
- }
- public static void AcceptCallback(IAsyncResult ar)
- {
- // Signal the main thread to continue.
- allDone.Set();
- // Get the socket that handles the client request.
- Socket listener = (Socket)ar.AsyncState;
- Socket handler = listener.EndAccept(ar);
- // Create the state object.
- StateObject state = new StateObject();
- //Store state instance in stateshandler
- stateshandler.States.Add(state);
- stateshandler.Counter+=1;
- state.workSocket = handler;
- handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
- new AsyncCallback(ReadCallback), state);
- listener.BeginAccept(
- new AsyncCallback(AcceptCallback),
- listener);
- Console.WriteLine("Connection accepted from: " + handler.RemoteEndPoint.ToString());
- }
- public static void ReadCallback(IAsyncResult ar)
- {
- try
- {
- String content = String.Empty;
- // Retrieve the state object and the handler socket
- // from the asynchronous state object.
- StateObject state = (StateObject)ar.AsyncState;
- Socket handler = state.workSocket;
- // Read data from the client socket.
- int bytesRead = handler.EndReceive(ar);
- if (bytesRead > 0)
- {
- // There might be more data, so store the data received so far.
- state.sb.Append(Encoding.ASCII.GetString(
- state.buffer, 0, bytesRead));
- // Check for end-of-file tag. If it is not there, read
- // more data.
- content = state.sb.ToString();
- if (content != null)
- {
- // All the data has been read from the
- // client. Display it on the console.
- //Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
- // content.Length, content);
- // Echo the data back to the client.
- Send(ar, content);
- state.sb.Clear();
- }
- else
- {
- // Not all data received. Get more.
- try
- {
- handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
- new AsyncCallback(ReadCallback), state);
- }
- catch (Exception e)
- {
- Console.WriteLine(e);
- Console.Read();
- }
- }
- }
- }
- catch (Exception e)
- {
- Console.WriteLine("A connection has been terminated. Error:\n{0}", e);
- /*
- *
- * STATE OBJECTS HANDLER NEEDS TO STORE INDIVIDUAL STATE UNIQUE
- * IDENTIFIERS AS SOMETHING OTHER THAN A SEQUENCE OF INTEGERS
- * AS WE NEED TO REMOVE FROM THE LIST BY THAT UNIQUE ID
- *
- *
- *
- * ARGHHHHH
- */
- }
- }
- private static void Send(IAsyncResult ar, String data)
- {
- for (int i = 0; i < stateshandler.Counter; i++)
- {
- StateObject state = stateshandler.States[i];
- Socket handler = state.workSocket;
- // Convert the string data to byte data using ASCII encoding.
- byte[] byteData = Encoding.ASCII.GetBytes(data);
- if (state != (StateObject)ar.AsyncState)
- {
- // Begin sending the data to the remote device.
- handler.BeginSend(byteData, 0, byteData.Length, 0,
- new AsyncCallback(SendCallback), state);
- }
- }
- }
- private static void SendCallback(IAsyncResult ar)
- {
- try
- {
- // Retrieve the socket from the state object.
- StateObject state = (StateObject)ar.AsyncState;
- Socket handler = state.workSocket;
- // Complete sending the data to the remote device.
- int bytesSent = handler.EndSend(ar);
- //Console.WriteLine("Sent {0} bytes to client.", bytesSent);
- handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
- new AsyncCallback(ReadCallback), state);
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- Console.WriteLine("\nPress ENTER to continue...");
- Console.Read();
- }
- }
- public static int Main(String[] args)
- {
- try
- {
- StartListening();
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- Console.WriteLine("\nPress ENTER to continue...");
- Console.Read();
- }
- Console.Read();
- return 0;
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using Microsoft.Xna.Framework;
- using Microsoft.Xna.Framework.Audio;
- using Microsoft.Xna.Framework.Content;
- using Microsoft.Xna.Framework.GamerServices;
- using Microsoft.Xna.Framework.Graphics;
- using Microsoft.Xna.Framework.Input;
- using Microsoft.Xna.Framework.Media;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- namespace Networked_Sprite_Animation
- {
- /// <summary>
- /// This is the main type for your game
- /// </summary>
- public class Game : Microsoft.Xna.Framework.Game
- {
- Sprite sprite;
- GraphicsDeviceManager graphics;
- SpriteBatch spriteBatch;
- IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);
- Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- Transmit data = new Transmit();
- string buffer;
- public Game()
- {
- graphics = new GraphicsDeviceManager(this);
- Content.RootDirectory = "Content";
- }
- /// <summary>
- /// Allows the game to perform any initialization it needs to before starting to run.
- /// This is where it can query for any required services and load any non-graphic
- /// related content. Calling base.Initialize will enumerate through any components
- /// and initialize them as well.
- /// </summary>
- protected override void Initialize()
- {
- Networked_Sprite_Animation.Client.Connect(localEndPoint, sock);
- base.Initialize();
- }
- /// <summary>
- /// LoadContent will be called once per game and is the place to load
- /// all of your content.
- /// </summary>
- protected override void LoadContent()
- {
- spriteBatch = new SpriteBatch(GraphicsDevice);
- sprite = new Sprite(Content.Load<Texture2D>("SpriteSheet"), 1, 32, 48);
- sprite.Position = new Vector2(400, 300);
- }
- /// <summary>
- /// UnloadContent will be called once per game and is the place to unload
- /// all content.
- /// </summary>
- protected override void UnloadContent()
- {
- // TODO: Unload any non ContentManager content here
- }
- /// <summary>
- /// Allows the game to run logic such as updating the world,
- /// checking for collisions, gathering input, and playing audio.
- /// </summary>
- /// <param name="gameTime">Provides a snapshot of timing values.</param>
- protected override void Update(GameTime gameTime)
- {
- sprite.HandleSpriteMovement(gameTime);
- // Allows the game to exit
- if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
- this.Exit();
- buffer = sprite.Texture.ToString() + sprite.SourceRect.ToString() + sprite.Position.ToString() + sprite.Origin.ToString();
- for (int i = 0; i < 3; i++)
- {
- Client.Send(sock, buffer);
- }
- base.Update(gameTime);
- }
- /// <summary>
- /// This is called when the game should draw itself.
- /// </summary>
- /// <param name="gameTime">Provides a snapshot of timing values.</param>
- protected override void Draw(GameTime gameTime)
- {
- GraphicsDevice.Clear(Color.DarkOliveGreen);
- spriteBatch.Begin();
- spriteBatch.Draw(sprite.Texture, sprite.Position, sprite.SourceRect, Color.White, 0f, sprite.Origin, 1.0f, SpriteEffects.None, 0);
- spriteBatch.End();
- base.Draw(gameTime);
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Client
- {
- public class Packet
- {
- byte[] bData;
- public Packet()
- {
- }
- public Packet(int data)
- {
- bData = Encoding.ASCII.GetBytes(data.ToString());
- }
- public byte[] getData()
- {
- return bData;
- }
- }
- }
Add Comment
Please, Sign In to add comment