Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
3.docx
Скачиваний:
2
Добавлен:
28.08.2019
Размер:
1.35 Mб
Скачать

Код клиента и сервера на основе дэйтаграмм Код сервера

using System;

using System.Net;

using System.Net.Sockets;

namespace TcpServer

{

class Program

{

static void Main()

{

UdpClient client;

IPEndPoint endPoint;

byte[] arr;

endPoint = new IPEndPoint(0, 0);

client = new UdpClient(10000);

Console.WriteLine("Server started");

arr = client.Receive(ref endPoint);

Console.WriteLine("There is a message from client:\n");

Console.WriteLine(System.Text.Encoding.ASCII.GetString(arr));

Console.WriteLine("The message will be sent back");

client.Send(arr, arr.Length, endPoint);

client.Close();

Console.ReadLine();

}

}

}

Код клиента

using System;

using System.Net;

using Sock = System.Net.Sockets;

namespace TcpClient

{

class Program

{

static void Main()

{

var endPoint = new IPEndPoint(0, 0);

var client = new Sock.UdpClient(10001);

byte[] data = System.Text.Encoding.ASCII.GetBytes("test message");

Console.WriteLine("Sending data to server ...");

client.Send(data, data.Length, "192.168.0.101", 10000);

Console.WriteLine("Receiving data from server ...");

data = client.Receive(ref endPoint);

Console.WriteLine("data: {0}", System.Text.Encoding.ASCII.GetString(data));

Console.ReadLine();

}

}

}

Код клиентского и серверного приложений для игровой системы

Структура проектов

Код сборки Enums

Commands.cs

namespace Enums

{

public enum Commands : byte

{

None = 0,

Connect = 1,

YourMove = 2,

Progress = 3,

Message = 4

}

}

Stuff.cs

namespace Enums

{

public enum StuffType : byte

{

None = 0,

O = 1,

X = 2

}

}

Код сервера

Program.cs

using System.Net;

using System;

namespace GameServerApp

{

internal class Program

{

private static void Main()

{

var gameServer = new GameServer(IPAddress.Parse("192.168.0.101"), 3307);

gameServer.Start();

Console.ReadLine();

}

}

}

GameServer.cs

using System;

using System.IO;

using System.Net;

using System.Net.Sockets;

using Enums;

namespace GameServerApp

{

internal delegate void MyDel(TcpClient x, TcpClient o);

public class GameServer

{

private TcpListener listner;

private TcpClient waitingClient;

public GameServer(IPAddress iPAddress, Int32 port)

{

listner = new TcpListener(iPAddress, port);

}

public void Start()

{

listner.Start();

listner.BeginAcceptTcpClient(AcceptClient, null);

}

private void AcceptClient(IAsyncResult result)

{

StreamWriter sw;

var client = listner.EndAcceptTcpClient(result);

listner.BeginAcceptTcpClient(AcceptClient, null);

sw = new StreamWriter(client.GetStream());

sw.AutoFlush = true;

if (waitingClient == null)

{

waitingClient = client;

sw.WriteLine(GetConnectCommand(StuffType.X));

}

else

{

sw.WriteLine(GetConnectCommand(StuffType.O));

var xsw = new StreamWriter(waitingClient.GetStream());

xsw.WriteLine((byte)Commands.YourMove);

xsw.Flush();

new MyDel(InteractClients).BeginInvoke(waitingClient, client, null, null);

waitingClient = null;

}

}

private void InteractClients(TcpClient x, TcpClient o)

{

NetworkStream xn, on;

StreamReader xr, or;

StreamWriter xw, ow;

Boolean isXMove;

Int32 result, row, column, counter;

Int32[,] matrix;

String temp;

xn = x.GetStream();

on = o.GetStream();

xr = new StreamReader(xn);

or = new StreamReader(on);

xw = new StreamWriter(xn);

ow = new StreamWriter(on);

xw.AutoFlush = ow.AutoFlush = true;

isXMove = true;

counter = 0;

matrix = new Int32[3, 3];

for (Int32 i = 0; i < 3; ++i)

{

for (Int32 j = 0; j < 3; ++j)

{

matrix[i, j] = -1;

}

}

while ((result = WinnerIs(matrix)) == -1 && counter++ < 9)

{

if (isXMove)

{

temp = xr.ReadLine();

ow.WriteLine(temp);

}

else

{

temp = or.ReadLine();

xw.WriteLine(temp);

}

ParseProgressCommand(temp, out row, out column);

matrix[row, column] = isXMove ? 1 : 0;

isXMove = !isXMove;

}

if (result != -1)

{

xw.WriteLine(((Byte)Commands.Message).ToString() + "/" + (result == 1 ? "WIN" : "GAME OVER"));

ow.WriteLine(((Byte)Commands.Message).ToString() + "/" + (result == 1 ? "GAME OVER" : "WIN"));

}

else

{

xw.WriteLine(((Byte)Commands.Message).ToString() + "/draw a victory");

ow.WriteLine(((Byte)Commands.Message).ToString() + "/draw a victory");

}

xr.Close();

xw.Close();

or.Close();

ow.Close();

x.Close();

o.Close();

}

private Int32 WinnerIs(Int32[,] matrix)

{

Int32 winner = -1;

if (matrix.Length != 9)

{

throw new Exception("Invalid matrix format");

}

if (matrix[0, 0] == matrix[0, 1] && matrix[0, 1] == matrix[0, 2])

{

winner = matrix[0, 0];

}

else if (matrix[1, 0] == matrix[1, 1] && matrix[1, 1] == matrix[1, 2])

{

winner = matrix[1, 0];

}

else if (matrix[2, 0] == matrix[2, 1] && matrix[2, 1] == matrix[2, 2])

{

winner = matrix[2, 0];

}

else if (matrix[0, 0] == matrix[1, 0] && matrix[1, 0] == matrix[2, 0])

{

winner = matrix[0, 0];

}

else if (matrix[0, 1] == matrix[1, 1] && matrix[1, 1] == matrix[2, 1])

{

winner = matrix[0, 1];

}

else if (matrix[0, 2] == matrix[1, 2] && matrix[1, 2] == matrix[2, 2])

{

winner = matrix[0, 2];

}

else if (matrix[0, 0] == matrix[1, 1] && matrix[1, 1] == matrix[2, 2])

{

winner = matrix[0, 0];

}

else if (matrix[2, 0] == matrix[1, 1] && matrix[1, 1] == matrix[0, 2])

{

winner = matrix[2, 0];

}

return winner;

}

private String GetConnectCommand(StuffType stuff)

{

return String.Format("{0}/{1}", ((byte)Commands.Connect).ToString(), stuff.ToString());

}

private String GetMessageCommand(String message)

{

return String.Format("{0}/{1}", ((byte)Commands.Message).ToString(), message);

}

private void ParseProgressCommand(String command, out Int32 row, out Int32 column)

{

var values = command.Split('/');

row = Int32.Parse(values[1]);

column = Int32.Parse(values[2]);

}

}

}

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]