Projekt

Obecné

Profil

Stáhnout (7.49 KB) Statistiky
| Větev: | Tag: | Revize:
1
//// Asynchronous Client Socket Example
2
//// http://msdn.microsoft.com/en-us/library/bew39x2a.aspx
3

    
4
//using System;
5
//using System.Net;
6
//using System.Net.Sockets;
7
//using System.Threading;
8
//using System.Text;
9

    
10
//// State object for receiving data from remote device.
11
//public class StateObject
12
//{
13
//    // Client socket.
14
//    public Socket workSocket = null;
15
//    // Size of receive buffer.
16
//    public const int BufferSize = 256;
17
//    // Receive buffer.
18
//    public byte[] buffer = new byte[BufferSize];
19
//    // Received data string.
20
//    public StringBuilder sb = new StringBuilder();
21
//}
22

    
23
//public class AsynchronousClient
24
//{
25
//    // The port number for the remote device.
26
//    private const int port = 11000;
27

    
28
//    // ManualResetEvent instances signal completion.
29
//    private static ManualResetEvent connectDone =
30
//        new ManualResetEvent(false);
31
//    private static ManualResetEvent sendDone =
32
//        new ManualResetEvent(false);
33
//    private static ManualResetEvent receiveDone =
34
//        new ManualResetEvent(false);
35

    
36
//    // The response from the remote device.
37
//    private static String response = String.Empty;
38

    
39
//    private static void StartClient()
40
//    {
41
//        // Connect to a remote device.
42
//        try
43
//        {
44
//            // Establish the remote endpoint for the socket.
45
//            // The name of the 
46
//            // remote device is "host.contoso.com".
47
//            IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
48
//            IPAddress ipAddress = ipHostInfo.AddressList[0];
49
//            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Loopback, port);
50

    
51
//            // Create a TCP/IP socket.
52
//            Socket client = new Socket(AddressFamily.InterNetwork,
53
//                SocketType.Stream, ProtocolType.Tcp);
54

    
55
//            // Connect to the remote endpoint.
56
//            client.BeginConnect(remoteEP,
57
//                new AsyncCallback(ConnectCallback), client);
58
//            connectDone.WaitOne();
59

    
60
//            // Send test data to the remote device.
61
//            Send(client, "This is a test!");
62
//            sendDone.WaitOne();
63

    
64
//            // Receive the response from the remote device.
65
//            Receive(client);
66
//            receiveDone.WaitOne();
67

    
68
//            // Write the response to the console.
69
//            Console.WriteLine("Response received : {0}", response);
70

    
71
//            // Release the socket.
72
//            client.Shutdown(SocketShutdown.Both);
73
//            client.Close();
74

    
75
//        }
76
//        catch (Exception e)
77
//        {
78
//            Console.WriteLine(e.ToString());
79
//        }
80
//    }
81

    
82
//    private static void ConnectCallback(IAsyncResult ar)
83
//    {
84
//        try
85
//        {
86
//            // Retrieve the socket from the state object.
87
//            Socket client = (Socket)ar.AsyncState;
88

    
89
//            // Complete the connection.
90
//            client.EndConnect(ar);
91

    
92
//            Console.WriteLine("Socket connected to {0}",
93
//                client.RemoteEndPoint.ToString());
94

    
95
//            // Signal that the connection has been made.
96
//            connectDone.Set();
97
//        }
98
//        catch (Exception e)
99
//        {
100
//            Console.WriteLine(e.ToString());
101
//        }
102
//    }
103

    
104
//    private static void Receive(Socket client)
105
//    {
106
//        try
107
//        {
108
//            // Create the state object.
109
//            StateObject state = new StateObject();
110
//            state.workSocket = client;
111

    
112
//            // Begin receiving the data from the remote device.
113
//            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
114
//                new AsyncCallback(ReceiveCallback), state);
115
//        }
116
//        catch (Exception e)
117
//        {
118
//            Console.WriteLine(e.ToString());
119
//        }
120
//    }
121

    
122
//    private static void ReceiveCallback(IAsyncResult ar)
123
//    {
124
//        try
125
//        {
126
//            // Retrieve the state object and the client socket 
127
//            // from the asynchronous state object.
128
//            StateObject state = (StateObject)ar.AsyncState;
129
//            Socket client = state.workSocket;
130

    
131
//            // Read data from the remote device.
132
//            int bytesRead = client.EndReceive(ar);
133

    
134
//            if (bytesRead > 0)
135
//            {
136
//                // There might be more data, so store the data received so far.
137
//                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
138

    
139
//                // Get the rest of the data.
140
//                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
141
//                    new AsyncCallback(ReceiveCallback), state);
142
//            }
143
//            else
144
//            {
145
//                // All the data has arrived; put it in response.
146
//                if (state.sb.Length > 1)
147
//                {
148
//                    response = state.sb.ToString();
149
//                }
150
//                // Signal that all bytes have been received.
151
//                receiveDone.Set();
152
//            }
153
//        }
154
//        catch (Exception e)
155
//        {
156
//            Console.WriteLine(e.ToString());
157
//        }
158
//    }
159

    
160
//    private static void Send(Socket client, String data)
161
//    {
162
//        // Convert the string data to byte data using ASCII encoding.
163
//        byte[] byteData = Encoding.ASCII.GetBytes(data);
164

    
165
//        // Begin sending the data to the remote device.
166
//        client.BeginSend(byteData, 0, byteData.Length, 0,
167
//            new AsyncCallback(SendCallback), client);
168
//    }
169

    
170
//    private static void SendCallback(IAsyncResult ar)
171
//    {
172
//        try
173
//        {
174
//            // Retrieve the socket from the state object.
175
//            Socket client = (Socket)ar.AsyncState;
176

    
177
//            // Complete sending the data to the remote device.
178
//            int bytesSent = client.EndSend(ar);
179
//            Console.WriteLine("Sent {0} bytes to server.", bytesSent);
180

    
181
//            // Signal that all bytes have been sent.
182
//            sendDone.Set();
183
//        }
184
//        catch (Exception e)
185
//        {
186
//            Console.WriteLine(e.ToString());
187
//        }
188
//    }
189

    
190
//    public static void Main(String[] args)
191
//    {
192
//        StartClient();
193
//        Console.ReadLine();
194
//    }
195
//}
196

    
197

    
198

    
199

    
200
using System;
201
using System.Net.Sockets;
202
using System.Text;
203

    
204
class Program
205
{
206
    static int PORT_NO = 11000;
207
    const string SERVER_IP = "127.0.0.1";//"192.168.1.5";
208
    static void Main(string[] args)
209
    {
210
        //---data to send to the server---
211
        string textToSend = "ahoj!";
212

    
213
        Console.WriteLine("enter A if you are admin: ");
214
        string ent = "B";
215
        ent = Console.ReadLine();
216

    
217
		if (ent.Equals("A"))
218
		{
219
            PORT_NO = 10000;
220
		}
221
        //---create a TCPClient object at the IP and port no.---
222
        TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
223
        NetworkStream nwStream = client.GetStream();
224

    
225

    
226
		while (true)
227
		{
228
            Console.WriteLine("enter text: ");
229
            textToSend = Console.ReadLine();
230

    
231

    
232
            byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
233

    
234
            //---send the text---
235
            Console.WriteLine("Sending : " + textToSend);
236
            nwStream.Write(bytesToSend, 0, bytesToSend.Length);
237
			
238

    
239
            //---read back the text---
240
            byte[] bytesToRead = new byte[client.ReceiveBufferSize];
241
            int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
242
            Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
243

    
244
            if (textToSend.Equals("bye!"))
245
            {
246
                break;
247
            }
248
        }
249
        
250
        client.Close();
251
    }
252
}
(2-2/2)