Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
No results found
Show changes
Commits on Source (15)
Showing
with 1585 additions and 19 deletions
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
* text=auto eol=crlf
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
[Xx]64/
[Xx]86/
[Bb]uild/
bld/
[Bb]in/
[Oo]bj/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Un-comment the next line if you do not want to checkin
# your web deploy settings because they may include unencrypted
# passwords
#*.pubxml
*.publishproj
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directory
AppPackages/
BundleArtifacts/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# LightSwitch generated files
GeneratedArtifacts/
ModelManifest.xml
# Paket dependency manager
.paket/paket.exe
# FAKE - F# Make
.fake/

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FormClient", "FormClient\FormClient.csproj", "{BBFE43DE-6222-444C-BB2F-7F17A44F00A0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BBFE43DE-6222-444C-BB2F-7F17A44F00A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BBFE43DE-6222-444C-BB2F-7F17A44F00A0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BBFE43DE-6222-444C-BB2F-7F17A44F00A0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BBFE43DE-6222-444C-BB2F-7F17A44F00A0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FormClient
{
public enum Commande
{
POST, GET, HELP, QUIT, STOPSERVEUR, SUBSCRIBE, SUBSCRIBEv2, UNSUBSCRIBE, CREATEROOM
};
public enum CommandeType { REQUETE, REPONSE };
class ChatMessage
{
public const int bufferSize = 1500;
public Commande commande; // commande
public CommandeType commandeType; // type (Requête/Réponse)
public int dataSize; // taille de la donnée
public String data; // données de la commande
public String message; // Message
public String pseudo; // Pseudo
public ChatMessage(Commande commande, CommandeType type, String data)
{
this.commande = commande;
this.commandeType = type;
this.dataSize = data.Length;
this.data = data;
if (data.Contains('\0'))
{
this.pseudo = data.Split('\0')[0];
this.message = data.Split('\0')[1];
}
else
{
this.pseudo = null;
this.message = data;
}
}
public ChatMessage(byte[] buffer)
{
this.commande = (Commande)buffer[0];
this.commandeType = (CommandeType)buffer[1];
this.dataSize = BitConverter.ToInt32(buffer, 2);
this.data = Encoding.ASCII.GetString(buffer, sizeof(Int32) + 2, dataSize);
if (data.Contains('\0'))
{
this.pseudo = data.Split('\0')[0];
this.message = data.Split('\0')[1];
}
else
{
this.pseudo = null;
this.message = data;
}
}
public byte[] GetBytes()
{
byte[] buf = new byte[bufferSize];
buf[0] = Convert.ToByte((char)this.commande); // Commande
buf[1] = Convert.ToByte((char)this.commandeType); // Type de commande
int i = 2;
foreach (Byte b in BitConverter.GetBytes(dataSize)) // Taille des données
{
buf[i] = b;
i++;
}
foreach (Byte b in System.Text.Encoding.ASCII.GetBytes(data)) // Données
{
buf[i] = b;
i++;
}
return buf;
}
public static byte[] GetBytes(Commande commande, CommandeType type, String data)
{
ChatMessage chatCommande = new ChatMessage(commande, type, data);
return chatCommande.GetBytes();
}
public override string ToString()
{
return "[" + commande + "," + commandeType + ",\"" + pseudo + "\"," + dataSize + ",\"" + message + "\"]";
}
}
}
namespace FormClient
{
partial class FrmClient
{
/// <summary>
/// Variable nécessaire au concepteur.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Nettoyage des ressources utilisées.
/// </summary>
/// <param name="disposing">true si les ressources managées doivent être supprimées ; sinon, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Code généré par le Concepteur Windows Form
/// <summary>
/// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
/// le contenu de cette méthode avec l'éditeur de code.
/// </summary>
private void InitializeComponent()
{
this.btnGET = new System.Windows.Forms.Button();
this.btnSUB = new System.Windows.Forms.Button();
this.btnSTOP = new System.Windows.Forms.Button();
this.btnUNSUB = new System.Windows.Forms.Button();
this.rtbMSG = new System.Windows.Forms.RichTextBox();
this.txtMsg = new System.Windows.Forms.TextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.button3 = new System.Windows.Forms.Button();
this.btnCREATEROOM = new System.Windows.Forms.Button();
this.btnPOST = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// btnGET
//
this.btnGET.Location = new System.Drawing.Point(15, 26);
this.btnGET.Name = "btnGET";
this.btnGET.Size = new System.Drawing.Size(99, 23);
this.btnGET.TabIndex = 0;
this.btnGET.Tag = "1";
this.btnGET.Text = "GET";
this.btnGET.UseVisualStyleBackColor = true;
this.btnGET.Click += new System.EventHandler(this.btnClickSENDMSG);
//
// btnSUB
//
this.btnSUB.Location = new System.Drawing.Point(225, 26);
this.btnSUB.Name = "btnSUB";
this.btnSUB.Size = new System.Drawing.Size(99, 23);
this.btnSUB.TabIndex = 3;
this.btnSUB.Tag = "5";
this.btnSUB.Text = "SUBSCRIBE";
this.btnSUB.UseVisualStyleBackColor = true;
this.btnSUB.Click += new System.EventHandler(this.btnClickSENDMSG);
//
// btnSTOP
//
this.btnSTOP.Location = new System.Drawing.Point(120, 26);
this.btnSTOP.Name = "btnSTOP";
this.btnSTOP.Size = new System.Drawing.Size(99, 23);
this.btnSTOP.TabIndex = 2;
this.btnSTOP.Tag = "4";
this.btnSTOP.Text = "STOPSERVEUR";
this.btnSTOP.UseVisualStyleBackColor = true;
this.btnSTOP.Click += new System.EventHandler(this.btnClickSENDMSG);
//
// btnUNSUB
//
this.btnUNSUB.Location = new System.Drawing.Point(330, 26);
this.btnUNSUB.Name = "btnUNSUB";
this.btnUNSUB.Size = new System.Drawing.Size(99, 23);
this.btnUNSUB.TabIndex = 4;
this.btnUNSUB.Tag = "7";
this.btnUNSUB.Text = "UNSUBSCRIBE";
this.btnUNSUB.UseVisualStyleBackColor = true;
this.btnUNSUB.Click += new System.EventHandler(this.btnClickSENDMSG);
//
// rtbMSG
//
this.rtbMSG.Location = new System.Drawing.Point(13, 13);
this.rtbMSG.Name = "rtbMSG";
this.rtbMSG.Size = new System.Drawing.Size(561, 277);
this.rtbMSG.TabIndex = 5;
this.rtbMSG.Text = "";
//
// txtMsg
//
this.txtMsg.Location = new System.Drawing.Point(145, 300);
this.txtMsg.MaxLength = 1468;
this.txtMsg.Name = "txtMsg";
this.txtMsg.Size = new System.Drawing.Size(215, 20);
this.txtMsg.TabIndex = 6;
this.txtMsg.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtMsg_KeyDown);
this.txtMsg.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtMsg_KeyPress);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.button3);
this.groupBox1.Controls.Add(this.btnCREATEROOM);
this.groupBox1.Controls.Add(this.btnGET);
this.groupBox1.Controls.Add(this.btnSTOP);
this.groupBox1.Controls.Add(this.btnUNSUB);
this.groupBox1.Controls.Add(this.btnSUB);
this.groupBox1.Location = new System.Drawing.Point(13, 326);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(561, 83);
this.groupBox1.TabIndex = 7;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Commandes";
//
// button3
//
this.button3.Location = new System.Drawing.Point(225, 54);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(99, 23);
this.button3.TabIndex = 7;
this.button3.Tag = "5";
this.button3.Text = "LISTROOM";
this.button3.UseVisualStyleBackColor = true;
//
// btnCREATEROOM
//
this.btnCREATEROOM.Location = new System.Drawing.Point(435, 26);
this.btnCREATEROOM.Name = "btnCREATEROOM";
this.btnCREATEROOM.Size = new System.Drawing.Size(99, 23);
this.btnCREATEROOM.TabIndex = 5;
this.btnCREATEROOM.Tag = "8";
this.btnCREATEROOM.Text = "CREATEROOM";
this.btnCREATEROOM.UseVisualStyleBackColor = true;
this.btnCREATEROOM.Click += new System.EventHandler(this.btnClickSENDMSG);
//
// btnPOST
//
this.btnPOST.Location = new System.Drawing.Point(366, 297);
this.btnPOST.Name = "btnPOST";
this.btnPOST.Size = new System.Drawing.Size(75, 23);
this.btnPOST.TabIndex = 8;
this.btnPOST.Text = "ENVOYER";
this.btnPOST.UseVisualStyleBackColor = true;
this.btnPOST.Click += new System.EventHandler(this.btnPOST_Click);
//
// FrmClient
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(586, 433);
this.Controls.Add(this.btnPOST);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.txtMsg);
this.Controls.Add(this.rtbMSG);
this.Name = "FrmClient";
this.ShowIcon = false;
this.Text = "Room : global";
this.Load += new System.EventHandler(this.Form1_Load);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnGET;
private System.Windows.Forms.Button btnSUB;
private System.Windows.Forms.Button btnSTOP;
private System.Windows.Forms.Button btnUNSUB;
private System.Windows.Forms.RichTextBox rtbMSG;
private System.Windows.Forms.TextBox txtMsg;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button btnPOST;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button btnCREATEROOM;
}
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
namespace FormClient
{
public partial class FrmClient : Form
{
public FrmClient()
{
InitializeComponent();
}
/// <summary>
/// Pseudo
/// </summary>
string pseudo;
/// <summary>
/// Socket du client
/// </summary>
Socket clientSocket;
/// <summary>
/// Endpoint du serveur
/// </summary>
EndPoint serverEP;
/// <summary>
/// Function exectuée dans le thread : On ecoute le réseau et traite les messages reçu
/// </summary>
/// <param name="client">Socket du client</param>
/// <param name="server">EndPoint du serveur</param>
private void readNet(Socket client, EndPoint server)
{
try
{
byte[] buffer = new byte[1500];
while (true)
{
int nBytes = client.ReceiveFrom(buffer, buffer.Length, SocketFlags.None, ref server);
// Message reçu
ChatMessage receive = new ChatMessage(buffer);
Action action;
// On vide la rtb si on recoit la reponse d'un GET
if (receive.commandeType == CommandeType.REPONSE && receive.commande == Commande.GET){
action = () => rtbMSG.Text = "";
// Permet d'effacer tout les messages affichés dans le form
this.Invoke(action);
}
if (receive.commandeType == CommandeType.REPONSE){
// On affiche dans la console
Console.WriteLine(" < Reponse du serveur > " + receive.data);
}
else
{
// Split du message POST afin d'obtenir le pseudo et le message séparement
string[] splitted = receive.data.Split('\0');
if (receive.commande == Commande.GET)
{
// GET
action = () => rtbMSG.Text = '\n' + " <" + splitted[0] + "> " + splitted[1];
this.Invoke(action);
}
else
{
// AUTRES
action = () => rtbMSG.Text += '\n' + " <" + splitted[0] + "> " + splitted[1];
this.Invoke(action);
Console.WriteLine(" <" + splitted[0] + "> " + splitted[1]);
}
}
}
}
catch (Exception e)
{
// SERVEUR OFF => On ferme le client
Console.WriteLine("ERROR READ NET : Serveur fermé");
MessageBox.Show("Le serveur n'est pas disponible! Fermeture du client...");
Application.Exit();
}
}
/// <summary>
/// Se declenche au demarrage : initialisation du socket et des info utilisateurs
/// </summary>
private void Form1_Load(object sender, EventArgs e)
{
// ======================================== INITIALISATION ============================
// On demande le port du client et son pseudo
Console.WriteLine("Port(pas 11111)?");
int portClient = Convert.ToInt32(Console.ReadLine());
Console.WriteLine('\n' + "Pseudo?");
pseudo = Console.ReadLine();
// Si pseudo trop long => On truncate
if (pseudo.Length > 30)
pseudo = pseudo.Substring(0, 30);
// ===================================================================================
Console.WriteLine("=============================================");
Console.WriteLine("=============================================");
Console.WriteLine("================== CLIENT ===================");
Console.WriteLine("=============================================");
Console.WriteLine("=============================================" + '\n' + '\n');
// Coordonnées du serveur
string serverIP = "127.0.0.1";
int serverPort = 11111;
// Création de la socket du client
clientSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
// Liaison de la socket au point de communication
clientSocket.Bind(new IPEndPoint(IPAddress.Any, portClient));
// Création du EndPoint serveur
serverEP = new IPEndPoint(IPAddress.Parse(serverIP), serverPort);
// Creation et lancement du thread d'ecoute
Thread sendAll = new Thread(x => readNet(clientSocket, serverEP));
sendAll.Start();
// On change le focus
this.ActiveControl = txtMsg;
}
/// <summary>
/// Se declenche au click du bouton envoi: Envoi du message POST
/// </summary>
private void btnPOST_Click(object sender, EventArgs e)
{
ChatMessage m = new ChatMessage(Commande.POST, CommandeType.REQUETE, pseudo + '\0' + txtMsg.Text);
byte[] buffer = m.GetBytes();
// Envoi
clientSocket.SendTo(buffer, 0, buffer.Length, SocketFlags.None, serverEP);
txtMsg.Text = "";
}
/// <summary>
/// Se declenche au click d'un bouton: Envoi du message GET/SUB/UNSUB....
/// </summary>
private void btnClickSENDMSG(object sender,EventArgs e)
{
// On recupere le tag
int cmd = Convert.ToInt32(((Button)sender).Tag);
// On crée le message
ChatMessage m = new ChatMessage((Commande)cmd, CommandeType.REQUETE, txtMsg.Text);
byte[] buffer = m.GetBytes();
// Envoi du message
clientSocket.SendTo(buffer, 0, buffer.Length, SocketFlags.None, serverEP);
// On affiche le nom de la room dans le titre du form
if ((Commande)cmd == Commande.CREATEROOM)
this.Text = "Room : " + txtMsg.Text;
}
/// <summary>
/// On capture la touche entrée pour envoi le message POST
/// </summary>
private void txtMsg_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
btnPOST_Click(sender, e);
}
/// <summary>
/// On bloque la taille du message
/// </summary>
private void txtMsg_KeyPress(object sender, KeyPressEventArgs e)
{
if (((TextBox)sender).Text.Length > 1400 && (e.KeyChar != (char)Keys.Return || e.KeyChar != (char)Keys.Enter))
e.Handled = true;
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{BBFE43DE-6222-444C-BB2F-7F17A44F00A0}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>FormClient</RootNamespace>
<AssemblyName>FormClient</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ChatMessage.cs" />
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FormClient
{
static class Program
{
/// <summary>
/// Point d'entrée principal de l'application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmClient());
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("FormClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FormClient")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("bbfe43de-6222-444c-bb2f-7f17a44f00a0")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
//------------------------------------------------------------------------------
// <auto-generated>
// Ce code a été généré par un outil.
// Version du runtime :4.0.30319.42000
//
// Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si
// le code est régénéré.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FormClient.Properties
{
/// <summary>
/// Une classe de ressource fortement typée destinée, entre autres, à la consultation des chaînes localisées.
/// </summary>
// Cette classe a été générée automatiquement par la classe StronglyTypedResourceBuilder
// à l'aide d'un outil, tel que ResGen ou Visual Studio.
// Pour ajouter ou supprimer un membre, modifiez votre fichier .ResX, puis réexécutez ResGen
// avec l'option /str ou régénérez votre projet VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Retourne l'instance ResourceManager mise en cache utilisée par cette classe.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FormClient.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Remplace la propriété CurrentUICulture du thread actuel pour toutes
/// les recherches de ressources à l'aide de cette classe de ressource fortement typée.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
\ No newline at end of file
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FormClient.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClientUdp
{
public enum Commande
{
POST, GET, HELP, QUIT, STOPSERVEUR, SUBSCRIBE, SUBSCRIBEv2, UNSUBSCRIBE
};
public enum CommandeType { REQUETE, REPONSE };
class ChatMessage
{
public const int bufferSize = 1500;
public Commande commande; // commande
public CommandeType commandeType; // type (Requête/Réponse)
public int dataSize; // taille de la donnée
public String data; // données de la commande
public String message; // Message
public String pseudo; // Pseudo
public ChatMessage(Commande commande, CommandeType type, String data)
{
this.commande = commande;
this.commandeType = type;
this.dataSize = data.Length;
this.data = data;
if (data.Contains('\0'))
{
this.pseudo = data.Split('\0')[0];
this.message = data.Split('\0')[1];
}
else
{
this.pseudo = null;
this.message = data;
}
}
public ChatMessage(byte[] buffer)
{
this.commande = (Commande)buffer[0];
this.commandeType = (CommandeType)buffer[1];
this.dataSize = BitConverter.ToInt32(buffer, 2);
this.data = Encoding.ASCII.GetString(buffer, sizeof(Int32)+2, dataSize);
if (data.Contains('\0'))
{
this.pseudo = data.Split('\0')[0];
this.message = data.Split('\0')[1];
}
else
{
this.pseudo = null;
this.message = data;
}
}
public byte[] GetBytes()
{
byte[] buf = new byte[bufferSize];
buf[0] = Convert.ToByte((char)this.commande); // Commande
buf[1] = Convert.ToByte((char)this.commandeType); // Type de commande
int i = 2;
foreach (Byte b in BitConverter.GetBytes(dataSize)) // Taille des données
{
buf[i] = b;
i++;
}
foreach (Byte b in System.Text.Encoding.ASCII.GetBytes(data)) // Données
{
buf[i] = b;
i++;
}
return buf;
}
public static byte[] GetBytes(Commande commande, CommandeType type, String data)
{
ChatMessage chatCommande = new ChatMessage(commande, type, data);
return chatCommande.GetBytes();
}
public override string ToString()
{
return "[" + commande + "," + commandeType + ",\"" + pseudo + "\"," + dataSize + ",\"" + message + "\"]";
}
}
}
......@@ -5,19 +5,60 @@ using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ClientUdp
{
class ClientUdp
{
static void readNet(Socket client,EndPoint server)
{
try
{
byte[] buffer = new byte[1500];
while (true)
{
int nBytes = client.ReceiveFrom(buffer, buffer.Length, SocketFlags.None, ref server);
ChatMessage receive = new ChatMessage(buffer);
if (receive.commandeType == CommandeType.REPONSE)
{
Console.WriteLine(" <Reponse du serveur> " + receive.data);
}
else
{
string[] splitted = receive.data.Split('\0');
Console.WriteLine(" <" + splitted[0] + "> " + splitted[1]);
}
}
}
catch(Exception e)
{
Console.WriteLine("ERROR READ NET : Serveur fermé");
}
}
static void Main(string[] args)
{
Console.WriteLine("Port(pas 11111)?");
int portClient = Convert.ToInt32(Console.ReadLine());
Console.WriteLine('\n' + "Pseudo?");
string pseudo = Console.ReadLine();
try
{
//************************************************************** Initialisation
string serverIP = "0.0.0.0"; // A changer
int serverPort = 000000 ; // A changer
Console.WriteLine("=============================================");
Console.WriteLine("=============================================");
Console.WriteLine("================== CLIENT ===================");
Console.WriteLine("=============================================");
Console.WriteLine("=============================================" + '\n' + '\n');
string serverIP = "127.0.0.1"; // A changer
int serverPort = 11111 ; // A changer
// Création de la socket d'écoute UDP
......@@ -28,39 +69,57 @@ namespace ClientUdp
// Liaison de la socket au point de communication
clientSocket.Bind(new IPEndPoint(IPAddress.Any, 22222));
clientSocket.Bind(new IPEndPoint(IPAddress.Any, portClient));
// Création du EndPoint serveur
EndPoint serverEP = new IPEndPoint(IPAddress.Parse(serverIP), serverPort);
Thread sendAll = new Thread(x => readNet(clientSocket, serverEP));
sendAll.Start();
// Lecture message au clavier
Console.Write("? ");
String msg = Console.ReadLine();
bool loop = true;
while (loop)
{
Console.WriteLine('\n' + "Commande? (Help: 2)");
int cmd = Convert.ToInt32(Console.ReadLine());
if (cmd == 3) // QUIT
loop = false;
//************************************************************** Communications
// Encodage du string dans un buffer de bytes en ASCII
byte[] buffer = System.Text.Encoding.ASCII.GetBytes(msg);
Console.WriteLine("Taille buffer : "+buffer.Length);
string dat = "";
if (cmd == 0) // POST
{
Console.WriteLine('\n' + "Message?");
dat = Console.ReadLine();
}
// Envoie du message au serveur
int nBytes = clientSocket.SendTo(buffer, 0, buffer.Length, SocketFlags.None, serverEP);
// Lecture message au clavier
ChatMessage m;
if(cmd == 0)
m = new ChatMessage((Commande)cmd, CommandeType.REQUETE, pseudo + '\0' +dat);
else
m = new ChatMessage((Commande)cmd, CommandeType.REQUETE, dat);
Console.WriteLine("Nouveau message envoye vers "
+ serverEP
+ " (" + nBytes + " octets)"
+ ": \"" + msg + "\"");
//************************************************************** Communications
// Encodage du string dans un buffer de bytes en ASCII
byte[] buffer = m.GetBytes();
// Envoie du message au serveur
int nBytes = clientSocket.SendTo(buffer, 0, buffer.Length, SocketFlags.None, serverEP);
Thread.Sleep(100);
}
//************************************************************** Conclusion
// Fermeture socket
Console.WriteLine("Fermeture Socket...");
clientSocket.Close();
Thread.Sleep(500);
Environment.Exit(0);
}
catch (SocketException E)
{
......
......@@ -58,6 +58,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ChatMessage.cs" />
<Compile Include="ClientUdp.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
......

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual C# Express 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "serveurUdp", "serveurUdp\serveurUdp.csproj", "{7FD485EB-1D1E-4208-868C-5994E555E8AE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7FD485EB-1D1E-4208-868C-5994E555E8AE}.Debug|x86.ActiveCfg = Debug|x86
{7FD485EB-1D1E-4208-868C-5994E555E8AE}.Debug|x86.Build.0 = Debug|x86
{7FD485EB-1D1E-4208-868C-5994E555E8AE}.Release|x86.ActiveCfg = Release|x86
{7FD485EB-1D1E-4208-868C-5994E555E8AE}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ServeurUdp
{
public enum Commande
{
POST, GET, HELP, QUIT, STOPSERVEUR, SUBSCRIBE, SUBSCRIBEv2, UNSUBSCRIBE, CREATEROOM
};
public enum CommandeType { REQUETE, REPONSE };
class ChatMessage
{
public const int bufferSize = 1500;
public Commande commande; // commande
public CommandeType commandeType; // type (Requête/Réponse)
public int dataSize; // taille de la donnée
public String data; // données de la commande
public String message; // Message
public String pseudo; // Pseudo
public ChatMessage(Commande commande, CommandeType type, String data)
{
this.commande = commande;
this.commandeType = type;
this.dataSize = data.Length;
this.data = data;
if (data.Contains('\0'))
{
this.pseudo = data.Split('\0')[0];
this.message = data.Split('\0')[1];
}
else
{
this.pseudo = null;
this.message = data;
}
}
public ChatMessage(byte[] buffer)
{
this.commande = (Commande)buffer[0];
this.commandeType = (CommandeType)buffer[1];
this.dataSize = BitConverter.ToInt32(buffer, 2);
this.data = Encoding.ASCII.GetString(buffer, sizeof(Int32) + 2, dataSize);
if (data.Contains('\0'))
{
this.pseudo = data.Split('\0')[0];
this.message = data.Split('\0')[1];
}
else
{
this.pseudo = null;
this.message = data;
}
}
public byte[] GetBytes()
{
byte[] buf = new byte[bufferSize];
buf[0] = Convert.ToByte((char)this.commande); // Commande
buf[1] = Convert.ToByte((char)this.commandeType); // Type de commande
int i = 2;
foreach (Byte b in BitConverter.GetBytes(dataSize)) // Taille des données
{
buf[i] = b;
i++;
}
foreach (Byte b in System.Text.Encoding.ASCII.GetBytes(data)) // Données
{
buf[i] = b;
i++;
}
return buf;
}
public static byte[] GetBytes(Commande commande, CommandeType type, String data)
{
ChatMessage chatCommande = new ChatMessage(commande, type, data);
return chatCommande.GetBytes();
}
public override string ToString()
{
return "[" + commande + "," + commandeType + ",\"" + pseudo + "\"," + dataSize + ",\"" + message + "\"]";
}
}
}