Назначение программы:
Программа предназначена для обмена сообщениями по сети.
Условия выполнения программы
Минимальные требования.
1. Системные требования:
Операционной системы Windows ХР, Windows 7;Office XP/2003/2007/2010.
2. Аппаратные требования:
Принтер (для печати отчетов и шаблонов справок);
Процессор Intel Pentium IV с тактовой частотой 2.0 GHz и выше;
МБ оперативной памяти
Не менее 30 МБ свободного дискового пространства для установки приложения
2 Порядок установки и настройки системы:
· Распаковываем архив с программой в нужную директорию;
· Запустите программу;
· Запустите клиенты на разных машинах;
· Отправьте тестовое сообщение
Если на данном этапе не возникло ошибок - система корректно установлена и работоспособна, технические требования соблюдены.
Выполнение программы
Запустите и настройте сервер, прописав ему IP вашей сети и нажмите на кнопку Начать прослушку. Сервер начнет прослушку порта.
Запустите клиенты и введите в них IP вашей сети, введите свой никнейм в чате и нажмите на кнопку Connect.
Приложение 2
Документированный листинг
Сервер
using System;
using System.Collections.Generic;System.ComponentModel;System.Data;System.Drawing;System.Text;System.Windows.Forms;System.Threading;System.Net;System.Net.Sockets;System.IO;ChatServer
{partial class Form1: Form
{delegate void UpdateStatusCallback(string strMessage);Form1()
{();
}void btnListen_Click(object sender, EventArgs e)
{
// Parse the server's IP address out of the TextBoxipAddr = IPAddress.Parse(txtIp.Text);
// Create a new instance of the ChatServer objectmainServer = new ChatServer(ipAddr);
// Hook the StatusChanged event handler to mainServer_StatusChanged.StatusChanged += new StatusChangedEventHandler (mainServer_StatusChanged);
// Start listening for connections.StartListening();
// Show that we started to listen for connections.AppendText("Monitoring for connections...\r\n");
}void mainServer_StatusChanged(object sender, StatusChanged EventArgs e)
{
// Call the method that updates the form.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage });
}void UpdateStatus(string strMessage)
{
// Updates the log with the message.AppendText(strMessage + "\r\n");
}
}
}
Клиент
System;System.Collections.Generic;System.ComponentModel;System.Data;System.Drawing;System.Text;System.Windows.Forms;System.Net;System.Net.Sockets;System.IO;System.Threading;ChatClient
{partial class Form1: Form
{
// Will hold the user namestring UserName = "Unknown";StreamWriter swSender;StreamReader srReceiver;TcpClient tcpServer;
// Needed to update the form with messages from another threaddelegate void UpdateLogCallback(string strMessage);
// Needed to set the form to a "disconnected" state from another threaddelegate void CloseConnectionCallback(string strReason);Thread thrMessaging;IPAddress ipAddr;bool Connected;Form1()
{
// On application exit, don't forget to disconnect first.ApplicationExit += new EventHandler(OnApplicationExit);();
}
// The event handler for application exitvoid OnApplicationExit(object sender, EventArgs e)
{(Connected == true)
{
// Closes the connections, streams, etc.= false;.Close();.Close();.Close();
}
}void btnConnect_Click(object sender, EventArgs e)
{
// If we are not currently connected but awaiting to connect(Connected == false)
{
// Initialize the connection();
}// We are connected, thus disconnect
{("Disconnected at user's request.");
}
}void InitializeConnection()
{
// Parse the IP address from the TextBox into an IPAddress object= IPAddress.Parse(txtIp.Text);
// Start a new TCP connections to the chat server= new TcpClient();.Connect(ipAddr, 1986);
// Helps us track whether we're connected or not= true;
// Prepare the form= txtUser.Text;
// Disable and enable the appropriate fields.Enabled = false;.Enabled = false;.Enabled = true;.Enabled = true;.Text = "Disconnect";
// Send the desired username to the server= new StreamWriter(tcpServer.GetStream());.WriteLine(txtUser.Text);.Flush();
// Start the thread for receiving messages and further communication= new Thread(new ThreadStart(ReceiveMessages));.Start();
}void ReceiveMessages()
{
// Receive the response from the server= new StreamReader(tcpServer.GetStream());
// If the first character of the response is 1, connection was successfulConResponse = srReceiver.ReadLine();
// If the first character is a 1, connection was successful(ConResponse[0] == '1')
{
// Update the form to tell it we are now connected.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { "Connected Successfully!" });
}// If the first character is not a 1 (probably a 0), the connection was unsuccessful
{Reason = "Not Connected: ";
// Extract the reason out of the response message. The reason starts at the 3rd character+= ConResponse.Substring(2, ConResponse.Length - 2);
// Update the form with the reason why we couldn't connect.Invoke(new CloseConnectionCallback(this.CloseConnection), new object[] { Reason });
// Exit the method;
}
// While we are successfully connected, read incoming lines from the server(Connected)
{
// Show the messages in the log TextBox.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { srReceiver.ReadLine() });
}
}
// This method is called from a different thread in order to update the log TextBoxvoid UpdateLog(string strMessage)
{
// Append text also scrolls the TextBox to the bottom each time.AppendText(strMessage + "\r\n");
}
// Closes a current connectionvoid CloseConnection(string Reason)
{
// Show the reason why the connection is ending.AppendText(Reason + "\r\n");
// Enable and disable the appropriate controls on the form.Enabled = true;.Enabled = true;.Enabled = false;.Enabled = false;.Text = "Connect";
// Close the objects= false;.Close();.Close();.Close();
}
// Sends the message typed in to the servervoid SendMessage()
{(txtMessage.Lines.Length >= 1)
{.WriteLine(txtMessage.Text);.Flush();.Lines = null;
}.Text = "";
}
// We want to send the message when the Send button is clickedvoid btnSend_Click(object sender, EventArgs e)
{();
}
// But we also want to send the message once Enter is pressedvoid txtMessage_KeyPress(object sender, KeyPressEventArgs e)
{
// If the key is Enter(e.KeyChar == (char)13)
{();
}
}
}
}