PDA

View Full Version : برنامه چت



sahar_ra86
چهارشنبه 28 فروردین 1387, 10:46 صبح
سلام
من میخوام برنامه چت رو با c# بنویسم با تکنولوژی سوکت .ولی نمیدونم باید از کجا شروع کنم و توابع سمت کلاینت و سرور رو هم بلد نیستم .میشه منو راهنمایی کنید؟
با تشکر:عصبانی++:

khosro hoseini
چهارشنبه 28 فروردین 1387, 11:17 صبح
سلام البته نوشتن چنین برنامه ای نیاز به آشنایی کافی با سی شارپ داره
برای این کا شما باید با مفاهیمی همچون thread,socket programingبه قدر کافی آشنا باشید.معمولا چنین برنامه های از دو برنامه تشکیل میشوند:
1)برنامه server
2)برنامه client
به این صورت که برنامه server بر روی یک کامپیوتر در شبکه نصب میشود و برنامه client بر روی سایر کامپیوتر ها .سرور به یک پورت خاص گوش میدهد و کلاینتها هم در خواست های خود را به آن پورت میفرستند. در زیر مثالی از server , client قرار داده ام.

سرور:


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.IO;
namespace ChatServer
{
// server that awaits client connections (one at a time) and
// allows a conversation between client and server
publicclass Server : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox inputTextBox;
private System.Windows.Forms.TextBox displayTextBox;
private Socket connection;
private Thread readThread;
private System.ComponentModel.Container components = null;
private NetworkStream socketStream;
private BinaryWriter writer;
private BinaryReader reader;

// default constructor
public Server()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
// create a new thread from the server
readThread = new Thread( new ThreadStart( RunServer ) );
readThread.Start();
}
///<summary>
/// Clean up any resources being used.
///</summary>
protectedoverridevoid Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
///<summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///</summary>
privatevoid InitializeComponent()
{
this.displayTextBox = new System.Windows.Forms.TextBox();
this.inputTextBox = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// displayTextBox
//
this.displayTextBox.Location = new System.Drawing.Point(8, 40);
this.displayTextBox.Multiline = true;
this.displayTextBox.Name = "displayTextBox";
this.displayTextBox.ReadOnly = true;
this.displayTextBox.Size = new System.Drawing.Size(272, 208);
this.displayTextBox.TabIndex = 1;
this.displayTextBox.Text = "";
//
// inputTextBox
//
this.inputTextBox.Location = new System.Drawing.Point(8, 8);
this.inputTextBox.Name = "inputTextBox";
this.inputTextBox.Size = new System.Drawing.Size(272, 20);
this.inputTextBox.TabIndex = 0;
this.inputTextBox.Text = "";
this.inputTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.inputTex tBox_KeyDown);
//
// Server
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 261);
this.Controls.Add(this.displayTextBox);
this.Controls.Add(this.inputTextBox);
this.Name = "Server";
this.Text = "Server";
this.Closing += new System.ComponentModel.CancelEventHandler(this.Serv er_Closing);
this.Load += new System.EventHandler(this.Server_Load);
this.ResumeLayout(false);
}
#endregion
[STAThread]
staticvoid Main()
{
Application.Run( new Server() );
}
protectedvoid Server_Closing(
object sender, CancelEventArgs e )
{
System.Environment.Exit( System.Environment.ExitCode );
}
// sends the text typed at the server to the client
protectedvoid inputTextBox_KeyDown(
object sender, KeyEventArgs e )
{
// sends the text to the client
try
{
if ( e.KeyCode == Keys.Enter && connection != null )
{
writer.Write( "SERVER>>> " + inputTextBox.Text );

displayTextBox.Text +=
"\r\nSERVER>>> " + inputTextBox.Text;
// if the user at the server signaled termination
// sever the connection to the client
if ( inputTextBox.Text == "TERMINATE" )
connection.Close();
inputTextBox.Clear();
}
}
catch ( SocketException )
{
displayTextBox.Text += "\nError writing object";
}
}
// allows a client to connect and displays the text it sends
publicvoid RunServer()
{
TcpListener listener;
int counter = 1;
// wait for a client connection and display the text
// that the client sends
try
{
// Step 1: create TcpListener
listener = new TcpListener( 5000 );
// Step 2: TcpListener waits for connection request
listener.Start();
// Step 3: establish connection upon client request
while ( true )
{
displayTextBox.Text = "Waiting for connection\r\n";
// accept an incoming connection
connection = listener.AcceptSocket();
// create NetworkStream object associated with socket
socketStream = new NetworkStream( connection );
// create objects for transferring data across stream
writer = new BinaryWriter( socketStream );
reader = new BinaryReader( socketStream );
displayTextBox.Text += "Connection " + counter +
" received.\r\n";
// inform client that connection was successfull
writer.Write( "SERVER>>> Connection successful" );
inputTextBox.ReadOnly = false;
string theReply = "";
// Step 4: read String data sent from client
do
{
try
{
// read the string sent to the server
theReply = reader.ReadString();
// display the message
displayTextBox.Text += "\r\n" + theReply;
}
// handle exception if error reading data
catch ( Exception )
{
break;
}
} while ( theReply != "CLIENT>>> TERMINATE" &&
connection.Connected );
displayTextBox.Text +=
"\r\nUser terminated connection";
// Step 5: close connection
inputTextBox.ReadOnly = true;
writer.Close();
reader.Close();
socketStream.Close();
connection.Close();
++counter;
}
} // end try
catch ( Exception error )
{
MessageBox.Show( error.ToString() );
}
}
privatevoid Server_Load(object sender, System.EventArgs e)
{

} // end method RunServer
} // end class Server
}


کلاینت


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.IO;
namespace ChatClient
{
///<summary>
/// connects to a chat server
///</summary>
publicclass Client : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox inputTextBox;
private System.Windows.Forms.TextBox displayTextBox;
private NetworkStream output;
private BinaryWriter writer;
private BinaryReader reader;
privatestring message = "";
private Thread readThread;
///<summary>
/// Required designer variable.
///</summary>
private System.ComponentModel.Container components = null;
// default constructor
public Client()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
readThread = new Thread( new ThreadStart( RunClient ) );
readThread.Start();
}
///<summary>
/// Clean up any resources being used.
///</summary>
protectedoverridevoid Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
///<summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///</summary>
privatevoid InitializeComponent()
{
this.inputTextBox = new System.Windows.Forms.TextBox();
this.displayTextBox = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// inputTextBox
//
this.inputTextBox.Location = new System.Drawing.Point(8, 8);
this.inputTextBox.Name = "inputTextBox";
this.inputTextBox.Size = new System.Drawing.Size(272, 20);
this.inputTextBox.TabIndex = 0;
this.inputTextBox.Text = "";
this.inputTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.inputTex tBox_KeyDown);
//
// displayTextBox
//
this.displayTextBox.Location = new System.Drawing.Point(8, 40);
this.displayTextBox.Multiline = true;
this.displayTextBox.Name = "displayTextBox";
this.displayTextBox.ReadOnly = true;
this.displayTextBox.Size = new System.Drawing.Size(272, 208);
this.displayTextBox.TabIndex = 1;
this.displayTextBox.Text = "";
//
// Client
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 261);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.displayTextBox,
this.inputTextBox});
this.Name = "Client";
this.Text = "Client";
this.Closing += new System.ComponentModel.CancelEventHandler(this.Clie nt_Closing);
this.ResumeLayout(false);
}
#endregion
[STAThread]
staticvoid Main()
{
Application.Run( new Client() );
}
protectedvoid Client_Closing(
object sender, CancelEventArgs e )
{
System.Environment.Exit( System.Environment.ExitCode );
}
// sends text the user typed to server
protectedvoid inputTextBox_KeyDown (
object sender, KeyEventArgs e )
{
try
{
if ( e.KeyCode == Keys.Enter )
{
writer.Write( "CLIENT>>> " + inputTextBox.Text );
displayTextBox.Text +=
"\r\nCLIENT>>> " + inputTextBox.Text;

inputTextBox.Clear();
}
}
catch ( SocketException )
{
displayTextBox.Text += "\nError writing object";
}
} // end method inputTextBox_KeyDown
// connect to server and display server-generated text
publicvoid RunClient()
{
TcpClient client;
// instantiate TcpClient for sending data to server
try
{
displayTextBox.Text += "Attempting connection\r\n";
// Step 1: create TcpClient and connect to server
client = new TcpClient();
client.Connect( "localhost", 5000 );
// Step 2: get NetworkStream associated with TcpClient
output = client.GetStream();
// create objects for writing and reading across stream
writer = new BinaryWriter( output );
reader = new BinaryReader( output );
displayTextBox.Text += "\r\nGot I/O streams\r\n";
inputTextBox.ReadOnly = false;

// loop until server signals termination
do
{
// Step 3: processing phase
try
{
// read message from server
message = reader.ReadString();
displayTextBox.Text += "\r\n" + message;
}
// handle exception if error in reading server data
catch ( Exception )
{
System.Environment.Exit(
System.Environment.ExitCode );
}
} while( message != "SERVER>>> TERMINATE" );

displayTextBox.Text += "\r\nClosing connection.\r\n";
// Step 4: close connection
writer.Close();
reader.Close();
output.Close();
client.Close();
Application.Exit();
}
// handle exception if error in establishing connection
catch ( Exception error )
{
MessageBox.Show( error.ToString() );
}
} // end method RunClient
} // end class Client
}

razavi_university
چهارشنبه 28 فروردین 1387, 11:55 صبح
سلام
من میخوام برنامه چت رو با c# بنویسم با تکنولوژی سوکت .ولی نمیدونم باید از کجا شروع کنم و توابع سمت کلاینت و سرور رو هم بلد نیستم .میشه منو راهنمایی کنید؟
با تشکر:عصبانی++:
دوست عزیز لطفا قبلا از ایجاد تاپیک جستجو کنید:عصبانی++:
دقیقا همین برنامه ای رو که شما نیاز دارید در قسمت نمونه برنامه های تالار وجود دارد

stahad1
جمعه 11 فروردین 1391, 22:35 عصر
سلام می خام بدونم که میشه هر دو را در یک کامپیوتر اجرا کنم و کار کنه

hjran abdpor
جمعه 11 فروردین 1391, 22:44 عصر
چرا نمیشه ، شما میتونید IP ها را ست کنید و از دو طرف از پورت 1024 به بعد شروع کنید و هر کاری خواستید انجام بدید ، یه نمونه پروژه قبلا در این مورد نوشته بودیم که حتی تو اینترنت کار میکرد ، فکر کنم یه جای تو همین تالار اپ کرده بودم ، اگه پیدا نکردی بگو تا برات بزارم.

acilios
شنبه 12 فروردین 1391, 09:12 صبح
سلام.


سلام
من میخوام برنامه چت رو با C#‎ بنویسم با تکنولوژی سوکت .ولی نمیدونم باید از کجا شروع کنم و توابع سمت کلاینت و سرور رو هم بلد نیستم .میشه منو راهنمایی کنید؟
با تشکر:عصبانی++:

http://barnamenevis.org/showthread.php?121111-TCP-IP-Socket-Programming-in-Framework.Net-2.0

http://msdn.microsoft.com/en-us/magazine/cc300760.aspx

موفق باشید.