PDA

View Full Version : برنامه سوکت با چند نخی



mammad_asir
شنبه 21 آبان 1390, 10:14 صبح
با سلام من یک برنامه نوشتم که یک پیغام رو از یک کلاینت میگیره و نشون میده و حال میخوام چند تا کلاینت در یک زمان بتونه بهش وصل بشه و فرم سرور در حین کار قفل نکنه یعنی آسنکرون باشه چطور این کار را انجام بدم البته من در این زمینه مبتدی هستم و میخوام روش اصولی این کار را یاد بگیرم. متشکر

uniqueboy_ara
شنبه 21 آبان 1390, 11:37 صبح
توی کتاب دایتل برای این کار یه مثال آورده که کد کامل برنامه ش اینه: ( نسخه سرور )

1 // Fig. 22.1: Server.cs
2 // Set up a Server that will receive a connection from a client,
3 // send a string to the client, and close the connection.
45
using System;
6 using System.Drawing;
7 using System.Collections;
8 using System.ComponentModel;
9 using System.Windows.Forms;
10 using System.Threading;
11 using System.Net.Sockets;
12 using System.IO;
13
14 // server that awaits client connections (one at a time) and
15 // allows a conversation between client and server
16 public class Server : System.Windows.Forms.Form
17 {
18 private System.Windows.Forms.TextBox inputTextBox;
19 private System.Windows.Forms.TextBox displayTextBox;
20 private Socket connection;
21 private Thread readThread;
22
23 private System.ComponentModel.Container components = null;
24 private NetworkStream socketStream;
25 private BinaryWriter writer;
26 private BinaryReader reader;
28 // default constructor
29 public Server()
30 {
31 InitializeComponent();
32
33 // create a new thread from the server
34 readThread = new Thread( new ThreadStart( RunServer ) );
35 readThread.Start();
36 }
37
38 // Visual Studio .NET generated code
39
40 [STAThread]
41 static void Main()
42 {
43 Application.Run( new Server() );
44 }
45
46 protected void Server_Closing(
47 object sender, CancelEventArgs e )
48 {
49 System.Environment.Exit( System.Environment.ExitCode );
50 }
51
52 // sends the text typed at the server to the client
53 protected void inputTextBox_KeyDown(
54 object sender, KeyEventArgs e )
55 {
56 // sends the text to the client
57 try
58 {
59 if ( e.KeyCode == Keys.Enter && connection != null )
60 {
61 writer.Write( "SERVER>>> " + inputTextBox.Text );
62
63 displayTextBox.Text +=
64 "\r\nSERVER>>> " + inputTextBox.Text;
65
66 // if the user at the server signaled termination
67 // sever the connection to the client
68 if ( inputTextBox.Text == "TERMINATE" )
69 connection.Close();
70
71 inputTextBox.Clear();
72 }
73 }
74 catch ( SocketException )
75 {
76 displayTextBox.Text += "\nError writing object";
77 }
78 } // inputTextBox_KeyDown
7980 // allows a client to connect and displays the text it sends
81 public void RunServer()
82 {
83 TcpListener listener;
84 int counter = 1;
85
86 // wait for a client connection and display the text
87 // that the client sends
88 try
89 {
90 // Step 1: create TcpListener
91 listener = new TcpListener( 5000 );
92
93 // Step 2: TcpListener waits for connection request
94 listener.Start();
95
96 // Step 3: establish connection upon client request
97 while ( true )
98 {
99 displayTextBox.Text = "Waiting for connection\r\n";
100
101 // accept an incoming connection
102 connection = listener.AcceptSocket();
103
104 // create NetworkStream object associated with socket
105 socketStream = new NetworkStream( connection );
106
107 // create objects for transferring data across stream
108 writer = new BinaryWriter( socketStream );
109 reader = new BinaryReader( socketStream );
110
111 displayTextBox.Text += "Connection " + counter +
112 " received.\r\n";
113
114 // inform client that connection was successfull
115 writer.Write( "SERVER>>> Connection successful" );
116
117 inputTextBox.ReadOnly = false;
118 string theReply = "";
119
120 // Step 4: read String data sent from client
121 do
122 {
123 try
124 {
125 // read the string sent to the server
126 theReply = reader.ReadString();
127
128 // display the message
129 displayTextBox.Text += "\r\n" + theReply;
130 }
131132 // handle exception if error reading data
133 catch ( Exception )
134 {
135 break;
136 }
137
138 } while ( theReply != "CLIENT>>> TERMINATE" &&
139 connection.Connected );
140
141 displayTextBox.Text +=
142 "\r\nUser terminated connection";
143
144 // Step 5: close connection
145 inputTextBox.ReadOnly = true;
146 writer.Close();
147 reader.Close();
148 socketStream.Close();
149 connection.Close();
150
151 ++counter;
152 }
153 } // end try
154
155 catch ( Exception error )
156 {
157 MessageBox.Show( error.ToString() );
158 }
159
160 } // end method RunServer
161
162 } // end class Server

uniqueboy_ara
شنبه 21 آبان 1390, 11:39 صبح
نسخه کلاینت

1 // Fig. 22.2: Client.cs
2 // Set up a Client that will read information sent from a Server
3 // and display the information.
45
using System;
6 using System.Drawing;
7 using System.Collections;
8 using System.ComponentModel;
9 using System.Windows.Forms;
10 using System.Threading;
11 using System.Net.Sockets;
12 using System.IO;
13
14 // connects to a chat server
15 public class Client : System.Windows.Forms.Form
16 {
17 private System.Windows.Forms.TextBox inputTextBox;
18 private System.Windows.Forms.TextBox displayTextBox;
19
20 private NetworkStream output;
21 private BinaryWriter writer;
22 private BinaryReader reader;
23
24 private string message = "";
25
26 private Thread readThread;
27
28 private System.ComponentModel.Container components = null;
29
30 // default constructor
31 public Client()
32 {
33 InitializeComponent();
34
35 readThread = new Thread( new ThreadStart( RunClient ) );
36 readThread.Start();
37 }
38
39 // Visual Studio .NET-generated code
40
41 [STAThread]
42 static void Main()
43 {
44 Application.Run( new Client() );
45 }
46
47 protected void Client_Closing(
48 object sender, CancelEventArgs e )
49 {
50 System.Environment.Exit( System.Environment.ExitCode );
51 }
52
53 // sends text the user typed to server
54 protected void inputTextBox_KeyDown (
55 object sender, KeyEventArgs e )
56 {
57 try
58 {
59 if ( e.KeyCode == Keys.Enter )
60 {
61 writer.Write( "CLIENT>>> " + inputTextBox.Text );
62
63 displayTextBox.Text +=
64 "\r\nCLIENT>>> " + inputTextBox.Text;
65
66 inputTextBox.Clear();
67 }
68 }
69 catch ( SocketException ioe )
70 {
71 displayTextBox.Text += "\nError writing object";
72 }
73
74 } // end method inputTextBox_KeyDown
75
76 // connect to server and display server-generated text
77 public void RunClient()
78 {
79 TcpClient client;
80
81 // instantiate TcpClient for sending data to server
82 try
83 {
84 displayTextBox.Text += "Attempting connection\r\n";
85
86 // Step 1: create TcpClient and connect to server
87 client = new TcpClient();
88 client.Connect( "localhost", 5000 );
89
90 // Step 2: get NetworkStream associated with TcpClient
91 output = client.GetStream();
92
93 // create objects for writing and reading across stream
94 writer = new BinaryWriter( output );
95 reader = new BinaryReader( output );
96
97 displayTextBox.Text += "\r\nGot I/O streams\r\n";
98
99 inputTextBox.ReadOnly = false;
100
101 // loop until server signals termination
102 do
103 {
104
105 // Step 3: processing phase
106 try
107 {
108 // read message from server
109 message = reader.ReadString();
110 displayTextBox.Text += "\r\n" + message;
111 }
112
113 // handle exception if error in reading server data
114 catch ( Exception )
115 {
116 System.Environment.Exit(
117 System.Environment.ExitCode );
118 }
119 } while( message != "SERVER>>> TERMINATE" );
120
121 displayTextBox.Text += "\r\nClosing connection.\r\n";
122
123 // Step 4: close connection
124 writer.Close();
125 reader.Close();
126 output.Close();
127 client.Close();
128 Application.Exit();
129 }
130
131 // handle exception if error in establishing connection
132 catch ( Exception error )
133 {
134 MessageBox.Show( error.ToString() );
135 }
136
137 } // end method RunClient
138
139 } // end class Client