[Исходник]помогите допилить месагер с шифрованием — HackZona.Ru

Валится на разных никах и валится при подключении нескольких клиентов. Знаю знаю говнокод но помощь нужна. Кто в C# шарит помогите пожалуйсто, сам уже задолбался. За основу брал какойто чат он вроде тоже в бэкапах гдето в папке есть. тут шифровалка отдельная которую я накодил и отдельно клиент — сервер с шифрованием. очень надеюсь на вашу помощь а не тупо на использовани моего кода в своих целях… [url]http://www.sendspace.com/file/id5az1[/url]

[Исходник]помогите допилить месагер с шифрованием

Сообщений в теме: 21
Нравится
Не нравится
Репутация: 0
Рейтинг: 2
Кол-во тем: 0
Сообщения: 0
Валится на разных никах и валится при подключении нескольких клиентов.
Знаю знаю говнокод но помощь нужна.
Кто в C# шарит помогите пожалуйсто, сам уже задолбался.
За основу брал какойто чат он вроде тоже в бэкапах гдето в папке есть.
тут шифровалка отдельная которую я накодил и отдельно клиент — сервер с шифрованием.

очень надеюсь на вашу помощь а не тупо на использовани моего кода в своих целях…

[url]http://www.sendspace.com/file/id5az1[/url]
Нравится
Не нравится
Репутация: 0
Рейтинг: 2
Кол-во тем: 0
Сообщения: 0
вот законченный «почти» проект. дело в том что запуская клиента из папки BIN неважно
Release или Debug он не конектится или вообще не обрабатывает нажатие кнопки
конекта… Если честно я запарился с ним. И если еще честнее писал первый раз
его пьяным. Но спустя два года после лечебки я вернулся и намерен допилить его.
и Далее делюсь им тут… Пригодиться может при наработках собственных месагеров.
Идея была разработка для моей тимы. Но тима распалась и теперь набрать новую очень
сложно. Если есть желающие то стучитесь на мыло [email][email protected][/email].
Но проблема то не в этом=)))) Проблема в том, что этот чертов месагер вынес мне все
мозги. У меня уже нет нервов. Вся моя жинь испоганилась с ним. Спасите во имя всех святых пророчиц Греции… аууу

[url]http://www.sendspace.com/file/4ldz7v[/url] вот ссылка на архив с клиентовыми сырками.
Пароль ty15
Нравится
Не нравится
Репутация: 0
Рейтинг: 2
Кол-во тем: 0
Сообщения: 0
Ну смари. Сырые сокеты в новых окошках, разрешены тольков драйверной модели.начиная с висты. Вопрос в том что сервисы венды работают на уровне ринг-0. Тепер собственно вопрос, функции (их имена и параметры) такиеже как и на уровне драйверов или можно юзать sendto, rcvfrom. Чтоб слать пакеты SYN/ACK. Конкретно меня ин ересует флуд пакетами для сервера. Какбы попроще выразиться, пишу код флудера для тестов
Нравится
Не нравится
Репутация: 0
Рейтинг: 2
Кол-во тем: 0
Сообщения: 0
Да. И еще подскажите если писать сырые сокеты и вызывать их как сервис из венды в семерке висте или восмерке с десяткой, они так работать будут или запрет распространяется и на сервисы. и какие там функции для этого используются или там все как в дровах? это так на будущее
Нравится
Не нравится
Репутация: 0
Рейтинг: 0
Кол-во тем: 0
Сообщения: 0
Тогда ничего не могу сказать, глюк среды, может кеш VS почистить? По поводу сокетов вообще ничего не понял…
Нравится
Не нравится
Репутация: 0
Рейтинг: 0
Кол-во тем: 0
Сообщения: 0
Нужно было код программы в пост вложить.
Нравится
Не нравится
Репутация: 0
Рейтинг: 0
Кол-во тем: 0
Сообщения: 0
вечерком гляну. Валится я так понял сервер…
Нравится
Не нравится
Репутация: 0
Рейтинг: 2
Кол-во тем: 0
Сообщения: 0
нет как раз сервер стоит что надо. клиенты сыпятся. отлетают как ракеты от шатла =) ыыы

забыл сказать студия 2013 нужна. если без нее то — из нее сырок надо копировать в новый проект
Нравится
Не нравится
Репутация: 0
Рейтинг: 0
Кол-во тем: 0
Сообщения: 0
ууу… Монстроподобная студия, вечно требующие обновления говнодотнеты...))

О чём это я?.. ах да.
Я говорю выложи код в посте (не файлом, а текстом), файл не качается (408 выдает).
Давно бы уж всё допилили.
Нравится
Не нравится
Репутация: 0
Рейтинг: 2
Кол-во тем: 0
Сообщения: 0
[B]Chat Server:[/B]
ChatServer.cs
[code]
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Collections;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace ChatServer
{
// Holds the arguments for the StatusChanged event
public class StatusChangedEventArgs: EventArgs
{
// The argument we're interested in is a message describing the event
private string EventMsg;

// Property for retrieving and setting the event message
public string EventMessage
{
get
{
return EventMsg;
}
set
{
EventMsg = value;
}
}

// Constructor for setting the event message
public StatusChangedEventArgs(string strEventMsg)
{
EventMsg = strEventMsg;
}
}

// This delegate is needed to specify the parameters we're passing with our event
public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e);

class ChatServer
{
// This hash table stores users and connections (browsable by user)
public static Hashtable htUsers = new Hashtable(30); // 30 users at one time limit
// This hash table stores connections and users (browsable by connection)
public static Hashtable htConnections = new Hashtable(30); // 30 users at one time limit
// 30 Users keys
public static Hashtable htClientPublicKeys = new Hashtable(30);
public static Hashtable htServerPublicKeys = new Hashtable(30);
public static Hashtable htServerPrivateKeys = new Hashtable(30);
// Will store the IP address passed to it
private IPAddress ipAddress;
private TcpClient tcpClient;
// The event and its argument will notify the form when a user has connected, disconnected, send message, etc.
public static event StatusChangedEventHandler StatusChanged;
private static StatusChangedEventArgs e;

// The constructor sets the IP address to the one retrieved by the instantiating object
public ChatServer(IPAddress address)
{
ipAddress = address;
}

// The thread that will hold the connection listener
private Thread thrListener;

// The TCP object that listens for connections
private TcpListener tlsClient;

// Will tell the while loop to keep monitoring for connections
bool ServRunning = false;

// Add the user to the hash tables
public static String AddUser(TcpClient tcpUser, string strUsername, string clientPublicKey)
{
// First add the username and associated connection to both hash tables
ChatServer.htUsers.Add(strUsername, tcpUser);
ChatServer.htConnections.Add(tcpUser, strUsername);
RSACryptoServiceProvider rsaServerKeysToken = new RSACryptoServiceProvider(2048);

ChatServer.htClientPublicKeys.Add(tcpUser, clientPublicKey);
ChatServer.htServerPublicKeys.Add(tcpUser, rsaServerKeysToken.ToXmlString(false));
ChatServer.htServerPrivateKeys.Add(tcpUser, rsaServerKeysToken.ToXmlString(true));

// Tell of the new connection to all other users and to the server form

return rsaServerKeysToken.ToXmlString(false);
}

// Remove the user from the hash tables
public static void RemoveUser(TcpClient tcpUser)
{
// If the user is there
if ((String)ChatServer.htConnections[tcpUser] != null)
{

String tcpUserName = (String)ChatServer.htConnections[tcpUser];

//MessageBox.Show(null, tcpUserName, «Server F# RemoveUser M# Has left»);// Remove the user from the hash table
ChatServer.htUsers.Remove(ChatServer.htConnections[tcpUser]);
ChatServer.htConnections.Remove(tcpUser);
ChatServer.htClientPublicKeys.Remove(tcpUser);
ChatServer.htServerPublicKeys.Remove(tcpUser);
ChatServer.htServerPrivateKeys.Remove(tcpUser);

// First show the information and tell the other users about the disconnection
SendAdminMessage(tcpUserName + " has left us");

}
}

// This is called when we want to raise the StatusChanged event
public static void OnStatusChanged(StatusChangedEventArgs e)
{
StatusChangedEventHandler statusHandler = StatusChanged;
if (statusHandler != null)
{
// Invoke the delegate
statusHandler(null, e);
}
}

// Send administrative messages
public static void SendAdminMessage(string Message)
{
StreamWriter swSenderSender;

// First of all, show in our application who says what
e = new StatusChangedEventArgs(«Administrator: » + Message);
OnStatusChanged(e);

// Create an array of TCP clients, the size of the number of users we have
TcpClient[] tcpClients = new TcpClient[ChatServer.htUsers.Count];
// Copy the TcpClient objects into the array
ChatServer.htUsers.Values.CopyTo(tcpClients, 0);
// Loop through the list of TCP clients
String[] clientKeyToken = new String[ChatServer.htClientPublicKeys.Count];
// Copy the TcpClient objects into the array
ChatServer.htClientPublicKeys.Values.CopyTo(clientKeyToken, 0);
for (int i = 0; i < tcpClients.Length; i++)
{
// Try sending a message to each
try
{
// If the message is blank or the connection is null, break out
if (Message.Trim() == "" || tcpClients == null)
{
RemoveUser(tcpClients);
//ChatServer.htUsers.Values.CopyTo(tcpClients, 0);
// Loop through the list of TCP clients
//clientKeyToken = new String[ChatServer.htClientPublicKeys.Count];
// Copy the TcpClient objects into the array
// ChatServer.htClientPublicKeys.Values.CopyTo(clientKeyToken, 0);
continue;
}
RSACryptoServiceProvider rsaCryptKeyMessage = new RSACryptoServiceProvider(2048);
rsaCryptKeyMessage.FromXmlString(clientKeyToken);
UTF8Encoding utf8 = new UTF8Encoding();
//String encryptedMessage = Convert.ToBase64String(rsaCryptKeyMessage.Encrypt(utf8.GetBytes(«Administrator: » + Message.Trim()), false));
// Send the message to the current user in the loop
swSenderSender = new StreamWriter(tcpClients.GetStream());
swSenderSender.WriteLine(Convert.ToBase64String(rsaCryptKeyMessage.Encrypt(utf8.GetBytes(«Administrator: » + Message.Trim()), false)));
swSenderSender.Flush();
swSenderSender = null;
}
catch // If there was a problem, the user is not there anymore, remove him
{
RemoveUser(tcpClients);
//ChatServer.htUsers.Values.CopyTo(tcpClients, 0);
// Loop through the list of TCP clients
//clientKeyToken = new String[ChatServer.htClientPublicKeys.Count];
// Copy the TcpClient objects into the array
//ChatServer.htClientPublicKeys.Values.CopyTo(clientKeyToken, 0);
}
}
}

// Send messages from one user to all the others
public static void SendMessage(string From, string msg)
{

StreamWriter swSenderSender;

// First of all, show in our application who says what


// Create an array of TCP clients, the size of the number of users we have
TcpClient[] tcpClients = new TcpClient[ChatServer.htUsers.Count];
// Copy the TcpClient objects into the array
ChatServer.htUsers.Values.CopyTo(tcpClients, 0);
String[] clientKeyToken = new String[ChatServer.htClientPublicKeys.Count];
// Copy the TcpClient objects into the array
ChatServer.htClientPublicKeys.Values.CopyTo(clientKeyToken, 0);
// Loop through the list of TCP clients

UTF8Encoding utf8 = new UTF8Encoding();
RSACryptoServiceProvider rsaClientMsg = new RSACryptoServiceProvider(2048);
rsaClientMsg.FromXmlString ((String)ChatServer.htServerPrivateKeys[ChatServer.htUsers[From]]);
msg = utf8.GetString(rsaClientMsg.Decrypt(Convert.FromBase64String(msg), false));

e = new StatusChangedEventArgs(From + " says: " + msg);
OnStatusChanged(e);
for (int i = 0; i < tcpClients.Length; i++)
{
// Try sending a message to each
try
{
// If the message is blank or the connection is null, break out
if (msg.Trim() == "" || tcpClients == null)
{
RemoveUser(tcpClients);
continue;
}

RSACryptoServiceProvider rsaCryptKeyMessage = new RSACryptoServiceProvider(2048);
rsaCryptKeyMessage.FromXmlString(clientKeyToken);

UTF8Encoding utf82 = new UTF8Encoding();
String encryptedMessage = Convert.ToBase64String(rsaCryptKeyMessage.Encrypt(utf82.GetBytes(From + " says: " + msg), false));


// Send the message to the current user in the loop
swSenderSender = new StreamWriter(tcpClients.GetStream());
swSenderSender.WriteLine(encryptedMessage);
swSenderSender.Flush();
swSenderSender = null;
// clientKeyToken = null;
}
catch // If there was a problem, the user is not there anymore, remove him
{
RemoveUser(tcpClients);
}
}
}

public void StartListening()
{

// Get the IP of the first network device, however this can prove unreliable on certain configurations
IPAddress ipaLocal = ipAddress;

// Create the TCP listener object using the IP of the server and the specified port
tlsClient = new TcpListener(1986);

// Start the TCP listener and listen for connections
tlsClient.Start();

// The while loop will check for true in this before checking for connections
ServRunning = true;

// Start the new tread that hosts the listener
thrListener = new Thread(KeepListening);
thrListener.Start();
}

private void KeepListening()
{
// While the server is running
while (ServRunning == true)
{
// Accept a pending connection
tcpClient = tlsClient.AcceptTcpClient();
// Create a new instance of Connection
Connection newConnection = new Connection(tcpClient);
}
}
}

// This class handels connections; there will be as many instances of it as there will be connected users
class Connection
{
TcpClient tcpClient;
// The thread that will send information to the client
private Thread thrSender;
private StreamReader srReceiver;
private StreamWriter swSender;
private string currUser;
private string strResponse;

// The constructor of the class takes in a TCP connection
public Connection(TcpClient tcpCon)
{
tcpClient = tcpCon;
// The thread that accepts the client and awaits messages
thrSender = new Thread(AcceptClient);
// The thread calls the AcceptClient() method
thrSender.Start();
}

private void CloseConnection()
{
// Close the currently open objects
tcpClient.Close();
srReceiver.Close();
swSender.Close();
thrSender.Abort();
}

// Occures when a new client is accepted
private void AcceptClient()
{
srReceiver = new System.IO.StreamReader(tcpClient.GetStream());
swSender = new System.IO.StreamWriter(tcpClient.GetStream());

// Read the account information from the client
currUser = srReceiver.ReadLine();
String[] userResponse = currUser.Split('|');
// We got a response from the client
if (currUser != "")
{

// Store the user name in the hash table
if (ChatServer.htUsers.Contains(userResponse[0]) == true)
{
// 0 means not connected
swSender.WriteLine(«0|This username already exists.»);
swSender.Flush();
CloseConnection();
return;
}
else if (userResponse[0] == «Administrator»)
{
// 0 means not connected
swSender.WriteLine(«0|This username is reserved.»);
swSender.Flush();
CloseConnection();
return;
}
else
{
// Add the user to the hash tables and start listening for messages from him
//MessageBox.Show(null, userResponse[1], userResponse[0]);
String clientKey = ChatServer.AddUser(tcpClient, userResponse[0], userResponse[1]);
// 1 means connected successfully
swSender.WriteLine(«1|» + clientKey);
swSender.Flush();


ChatServer.SendAdminMessage(userResponse[0] + " has joined us");
}
}
else
{
CloseConnection();
return;
}

try
{
// Keep waiting for a message from the user
while ((strResponse = srReceiver.ReadLine()) != "")
{
// If it's invalid, remove the user
if (strResponse == null)
{
ChatServer.RemoveUser(tcpClient);
CloseConnection();
continue;
}
else
{

//MessageBox.Show(null, strResponse, «Server F# AcceptClient M# strResponse»);
// Otherwise send the message to all the other users
ChatServer.SendMessage(userResponse[0], strResponse);
}
}
}
catch
{
// If anything went wrong with this user, disconnect him
ChatServer.RemoveUser(tcpClient);
}
}
}
}

[/code]

Form1.cs
[code]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace ChatServer
{
public partial class Form1: Form
{
private delegate void UpdateStatusCallback(string strMessage);

public Form1()
{
InitializeComponent();
}

private void btnListen_Click(object sender, EventArgs e)
{
// Parse the server's IP address out of the TextBox
IPAddress ipAddr = IPAddress.Parse(txtIp.Text);
// Create a new instance of the ChatServer object
ChatServer mainServer = new ChatServer(ipAddr);
// Hook the StatusChanged event handler to mainServer_StatusChanged
ChatServer.StatusChanged += new StatusChangedEventHandler(mainServer_StatusChanged);
// Start listening for connections
btnListen.Enabled = false;
mainServer.StartListening();
// Show that we started to listen for connections
txtLog.AppendText(«Monitoring for connections...\r\n»);
}

public void mainServer_StatusChanged(object sender, StatusChangedEventArgs e)
{
//// Call the method that updates the form
this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage });
}

private void UpdateStatus(string strMessage)
{
// Updates the log with the message
txtLog.AppendText(strMessage + "\r\n");
}

private void btnStopListen_Click(object sender, EventArgs e)
{
// mainServer.StopListening();
}
}
}
[/code]
Program.cs
[code]
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace ChatServer
{
static class Program
{
/// /// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
[/code]
Нравится
Не нравится
Репутация: 0
Рейтинг: 2
Кол-во тем: 0
Сообщения: 0
ChatClient
Form1.cs
[code]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Security.Cryptography;
namespace ChatClient
{
public partial class Form1: Form
{
// Will hold the user name
private string UserName = «Unknown»;
private StreamWriter swSender;
private StreamReader srReceiver;
private TcpClient tcpServer;
// Needed to update the form with messages from another thread
private delegate void UpdateLogCallback(string strMessage);
private delegate void UpdateKeysCallback(string keyMsg);
// Needed to set the form to a «disconnected» state from another thread
private delegate void CloseConnectionCallback(string strReason);
private Thread thrMessaging;
private IPAddress ipAddr;
private IPHostEntry ipHost;
private bool Connected;

RSACryptoServiceProvider rsaClientKeys;
RSACryptoServiceProvider rsaServerPublicKey = new RSACryptoServiceProvider(2048);


public Form1()
{
// On application exit, don't forget to disconnect first
Application.ApplicationExit += new EventHandler(OnApplicationExit);
InitializeComponent();
}

// The event handler for application exit
public void OnApplicationExit(object sender, EventArgs e)
{
if (Connected == true)
{
// Closes the connections, streams, etc.
Connected = false;
swSender.Close();
srReceiver.Close();
tcpServer.Close();
}
}

private void btnConnect_Click(object sender, EventArgs e)
{
// If we are not currently connected but awaiting to connect
if (Connected == false)
{
// Initialize the connection
InitializeConnection();
}
else // We are connected, thus disconnect
{
CloseConnection(«Disconnected at user's request.»);
}
}

private void InitializeConnection()
{
rsaClientKeys = new RSACryptoServiceProvider(2048);
//rsaClientPublicKey = new RSACryptoServiceProvider(2048);
//rsaClientPublicKey.FromXmlString(rsaClientPrivateKey.ToXmlString(false));
// Parse the IP address from the TextBox into an IPAddress object
ipAddr = IPAddress.Parse(txtIp.Text);
// Start a new TCP connections to the chat server
//tcpServer = new TcpClient();
//TcpClient tcpServer = new TcpClient(ip.ToString(), 8888);

//tcpServer.Connect(ipAddr, 1986);
//if (tcpServer.Connected == false) return;
ipHost = Dns.Resolve(txtIp.Text);
ipAddr = ipHost.AddressList[0];
try
{
tcpServer = new TcpClient(ipAddr.ToString(), 1986);
Connected = true;
}
catch
{
return;
}
// Helps us track whether we're connected or not

// Prepare the form
UserName = txtUser.Text;

// Disable and enable the appropriate fields
txtIp.Enabled = false;
txtUser.Enabled = false;
txtMessage.Enabled = true;
btnSend.Enabled = true;
btnConnect.Text = «Disconnect»;

// Send the desired username to the server
swSender = new StreamWriter(tcpServer.GetStream());
swSender.WriteLine(txtUser.Text + "|" + rsaClientKeys.ToXmlString(false));
swSender.Flush();
// Start the thread for receiving messages and further communication
thrMessaging = new Thread(new ThreadStart(ReceiveMessages));
thrMessaging.Start();
}

private void ReceiveMessages()
{
// Receive the response from the server
srReceiver = new StreamReader(tcpServer.GetStream());
// If the first character of the response is 1, connection was successful
string ConResponse = srReceiver.ReadLine();
// If the first character is a 1, connection was successful

if (ConResponse[0] == '1')
{
String[] serverResponse = ConResponse.Split('|');
if (serverResponse[0] == «1» && serverResponse[1] != "")
this.Invoke(new UpdateKeysCallback(this.UpdateKeys), new object[] { serverResponse[1] });
// Update the form to tell it we are now connected
this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { «msg:connected» });
}
else // If the first character is not a 1 (probably a 0), the connection was unsuccessful
{
string Reason = «Not Connected: »;
// Extract the reason out of the response message. The reason starts at the 3rd character
Reason += ConResponse.Substring(2, ConResponse.Length — 2);
// Update the form with the reason why we couldn't connect
this.Invoke(new CloseConnectionCallback(this.CloseConnection), new object[] { Reason });
// Exit the method
return;
}
//String dataString;
// While we are successfully connected, read incoming lines from the server
while (Connected) //while (Connected && (dataString = srReceiver.ReadLine()) != "")
{
//MessageBox.Show(null, dataString, «Client datastring»);
// Show the messages in the log TextBox
//if (dataString != null)
this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { srReceiver.ReadLine() });
//dataString = null;
}
}
// This metod is called from different thread in order to add server key in to crypto stream
private void UpdateKeys(String keyMsg)
{
rsaServerPublicKey.FromXmlString(keyMsg);
//MessageBox.Show(null, keyMsg, «Client F# UpdateKeys M# Server Public Key»);
}
// This method is called from a different thread in order to update the log TextBox
private void UpdateLog(string strMessage)
{
if (strMessage == «msg:connected»)
{
txtLog.AppendText(«Connected Successfully!\r\nYou can talking.:\r\n»);
}
else
{
UTF8Encoding utf8 = new UTF8Encoding();
//String messageFromServer = ;//Convert.FromBase64String(txtCryptoText.Text.Trim()

// Append text also scrolls the TextBox to the bottom each time
txtLog.AppendText(utf8.GetString(rsaClientKeys.Decrypt(Convert.FromBase64String(strMessage), false)) + "\r\n");
}
}

// Closes a current connection
private void CloseConnection(string Reason)
{
// Show the reason why the connection is ending
txtLog.AppendText(Reason + "\r\n");
// Enable and disable the appropriate controls on the form
txtIp.Enabled = true;
txtUser.Enabled = true;
txtMessage.Enabled = false;
btnSend.Enabled = false;
btnConnect.Text = «Connect»;

// Close the objects
Connected = false;
swSender.Close();
srReceiver.Close();

tcpServer.Close();
thrMessaging.Abort();
}

// Sends the message typed in to the server
private void SendMessage(String keysMessage = «0|0»)
{
if (txtMessage.Lines.Length >= 1)
{
UTF8Encoding utf8 = new UTF8Encoding();

swSender.WriteLine(Convert.ToBase64String(rsaServerPublicKey.Encrypt(utf8.GetBytes(txtMessage.Text), false)));
swSender.Flush();
txtMessage.Lines = null;
}
txtMessage.Text = "";
}

// We want to send the message when the Send button is clicked
private void btnSend_Click(object sender, EventArgs e)
{
SendMessage();
}

// But we also want to send the message once Enter is pressed
private void txtMessage_KeyPress(object sender, KeyPressEventArgs e)
{
// If the key is Enter
if (e.KeyChar == (char)13)
{
SendMessage();
}
}
}
}
[/code]
Program.cs

[code]
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace ChatClient
{
static class Program
{
/// /// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
[/code]
Нравится
Не нравится
Репутация: 0
Рейтинг: 2
Кол-во тем: 0
Сообщения: 0
пипец тут даже подсветки нет
качайте отсюда [url]http://yadi.sk/d/uyEAobbChV98v[/url]

EkZoD ты где =)??
Нравится
Не нравится
Репутация: 0
Рейтинг: 0
Кол-во тем: 0
Сообщения: 0
опять меня через k пишут…
вчера не смог посмотреть, сегодня утром бегло глянул, пока кофе пил. Отваливаются сразу все клиенты с ошибкой 10004
[code]System.IO.IOException не обработано
Message=Не удается прочитать данные из транспортного соединения: Операция блокирования прервана вызовом WSACancelBlockingCall.
Source=System
StackTrace:
в System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
в System.IO.StreamReader.ReadBuffer()
в System.IO.StreamReader.ReadLine()
в ChatClient.Form1.ReceiveMessages() в c:\Users\Илья\Downloads\Desktop (1)\GPlotClient\ChatClient\Form1.cs: строка 148
в System.Threading.ThreadHelper.ThreadStart_Context(Object state)
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
в System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Net.Sockets.SocketException
Message=Операция блокирования прервана вызовом WSACancelBlockingCall
Source=System
ErrorCode=10004
NativeErrorCode=10004
StackTrace:
в System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
в System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
InnerException: [/code]
предположительно, что все-таки сервер рвет все соединения, на что клиент не расчитан (кстати — баг). Далее нужно было бежать, НО у сервера есть 3 try-catch в которых он рвет соединение. Я бы туда брекпоинты поставил и на отладку. Но это опять таки до вечера…
Нравится
Не нравится
Репутация: 0
Рейтинг: 0
Кол-во тем: 0
Сообщения: 0
а вот и я=) Сижу в в реальном времени, впервые за 3 года бажу код в студии. Предыдущая версия не подтвердилась. Клиенты падают при подключении 3го клиента на коде сервера [code] swSenderSender = new StreamWriter(tcpClients.GetStream());
swSenderSender.WriteLine(Convert.ToBase64String(rsaCryptKeyMessage.Encrypt(utf8.GetBytes(«Administrator: » + Message.Trim()), false)));
swSenderSender.Flush();
swSenderSender = null;
[/code]конкретно на swSenderSender.Flush();

иду дальше…
Нравится
Не нравится
Репутация: 0
Рейтинг: 2
Кол-во тем: 0
Сообщения: 0
вот это в клиент
[code]
while (Connected) //while (Connected && (dataString = srReceiver.ReadLine()) != "")
{

// Show the messages in the log TextBox
//if (dataString != null)
String rcvMessage = srReceiver.ReadLine();
if (rcvMessage == "" || rcvMessage == "")
{
continue;

}
MessageBox.Show(null, rcvMessage, «Client datastring»);
this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { rcvMessage });
//dataString = null;
}
[/code]
добавил это и оно выдержало пять клиентов… потом отвалилось по одному.может гдето слишком быстро считывается информация?
насколько я знаю это конец даных как EOF в с++… може я ошибаюсь и тут снова прокол?
Нравится
Не нравится
Репутация: 0
Рейтинг: 0
Кол-во тем: 0
Сообщения: 0
Хорошо вчера темное нефильтрованное пошло, почти сразу спать ушел.
К делу:
На сервере нас интересуют 2 Hashtable: htUsers и htClientPublicKeys. При добавлении юзера соответственно добавляются значения в эти хештейблы по ключу соединения. Далее в SendAdminMessage() и SendMessage() мы зачем-то берем ОБЫЧНЫЕ массивы и копипастим туда содержимое данных хештейблов, считая при этом, что с индексами у нас все будет збс соответствовать. В результате идем в цикле по соединениям и криптуем не теми ключами.

Короче, в SendMessage() сделай так:[code] rsaCryptKeyMessage.FromXmlString(ChatServer.htClientPublicKeys[tcpClients].ToString());
//rsaCryptKeyMessage.FromXmlString(clientKeyToken);
[/code]Твоя строка закомментирована. По аналогии делаем в SendAdminMessage().
Нравится
Не нравится
Репутация: 0
Рейтинг: 2
Кол-во тем: 0
Сообщения: 0
УРАААА ПАБЕДААА.я столько мучался а ты за день ве решил=)))спасибо спасибо спасибо… и еще почему оно падает когда я жму дисконект.всмысле сам клиент вылетает неправильно.вылазит табличка отладить или закрыть приложение… я вродебы везде там поставил все тоже непойму… столько времени угробил на этот клиент что уже мозги неварят.
Нравится
Не нравится
Репутация: 0
Рейтинг: 0
Кол-во тем: 0
Сообщения: 0
[QUOTE=ixTor;144548]почему оно падает когда я жму дисконект.всмысле сам клиент вылетает неправильно.вылазит табличка отладить или закрыть приложение ..[/QUOTE]

Типичный косяк многопоточных приложений. Сначала убиваем поток и только потом общие данные.
Должно быть так:[code] private void CloseConnection(string Reason)
{
thrMessaging.Abort();
// Show the reason why the connection is ending
txtLog.AppendText(Reason + "\r\n");
// Enable and disable the appropriate controls on the form
txtIp.Enabled = true;
txtUser.Enabled = true;
txtMessage.Enabled = false;
btnSend.Enabled = false;
btnConnect.Text = «Connect»;

// Close the objects
Connected = false;
swSender.Close();
srReceiver.Close();

tcpServer.Close();
}[/code]
Нравится
Не нравится
Репутация: 0
Рейтинг: 2
Кол-во тем: 0
Сообщения: 0
тю. а я думал наоборот надо=) понял ошибку… даже неподумал об этом в начале

ребят а почему когда я запускаю клиента из папки Bin то он не работает? не реагирует на кнопку коннект…

версия релиз почемуто неработает
Нравится
Не нравится
Репутация: 0
Рейтинг: 0
Кол-во тем: 0
Сообщения: 0
Почисти bin и obj и пересобери и дебаг и релиз. По умолчанию у тебя пересобирается только дебаг. У меня русскоязычная студия — меню Построение (Build)-Пакетное построение.
Нравится
Не нравится
Репутация: 0
Рейтинг: 2
Кол-во тем: 0
Сообщения: 0
всеравно нестартует… чтото помойму нетак в проекте помимо сборок… собирал пересобирал обе версии… запускается но нехочет конектиться какбудто там пустая форма без кода в нутри.только кнопки и никакой реакции
Нравится
Не нравится
Репутация: 0
Рейтинг: 0
Кол-во тем: 0
Сообщения: 0
сами папки удалял?
Для того, чтобы отвечать в темах на форуме необходимо войти на сайт или зарегистрироваться.