Demo solution:
Client class
1: public class TcpClient
2: {
3: #region Fields and Properties
4:
5: private const int Port = 6666;
6: private readonly System.Net.Sockets.TcpClient _client;
7: private readonly Thread _clientThread;
8: private readonly IPEndPoint _ipEndPoint;
9:
10: public IPAddress IpAddress { get; set; }
11:
12: #endregion
13:
14: #region Constructors
15:
16: public TcpClient()
17: {
18: _client = new System.Net.Sockets.TcpClient();
19:
20: // Set default data
21: IpAddress = IPAddress.Parse("127.0.0.1");
22:
23: // Server end point
24: if (IpAddress != null) _ipEndPoint = new IPEndPoint(IpAddress, Port);
25:
26: _clientThread = new Thread(HandleServerCommunication);
27: }
28:
29: #endregion
30:
31: #region Events
32:
33: #region Delegates
34:
35: public delegate void ReceivedMessageEventHandle(System.Net.Sockets.TcpClient client, string message);
36:
37: #endregion
38:
39: public event ReceivedMessageEventHandle ReceivedMessage;
40:
41: #endregion
42:
43: #region Start/Stop Connect
44:
45: /// <summary>
46: /// Start connect server
47: /// </summary>
48: public bool StartConnect()
49: {
50: try
51: {
52: if (_client != null)
53: {
54: if (!_client.Connected)
55: _client.Connect(_ipEndPoint);
56: return _client.Connected;
57: }
58: return false;
59: }
60: catch
61: {
62: return false;
63: }
64: }
65:
66: /// <summary>
67: /// Stop connect server
68: /// </summary>
69: public void StopConnect()
70: {
71: if (_clientThread.ThreadState == ThreadState.Running)
72: _clientThread.Abort();
73: if (_client.Connected)
74: _client.Close();
75: }
76:
77: #endregion
78:
79: #region Client
80:
81: /// <summary>
82: /// Send message to server and create thread listen response message
83: /// </summary>
84: /// <param name="message">string message</param>
85: public bool SendMessage(string message)
86: {
87: if (_client != null && _client.Connected)
88: {
89: try
90: {
91: // Send request to Window Service
92: NetworkStream clientStream = _client.GetStream();
93:
94: var encoder = new ASCIIEncoding();
95: byte[] buffer = encoder.GetBytes(message);
96:
97: clientStream.Write(buffer, 0, buffer.Length);
98: clientStream.Flush();
99:
100: _clientThread.Start(_client);
101: return true;
102: }
103: catch
104: {
105: return false;
106: }
107: }
108: return false;
109: }
110:
111: /// <summary>
112: /// Listen response from server and call event ReceivedMessage
113: /// </summary>
114: /// <param name="client">connected client</param>
115: private void HandleServerCommunication(object client)
116: {
117: var tcpClient = (System.Net.Sockets.TcpClient) client;
118: NetworkStream clientStream = tcpClient.GetStream();
119:
120: var message = new byte[4096];
121:
122: while (true)
123: {
124: int bytesRead;
125: try
126: {
127: //blocks until a client sends a message
128: bytesRead = clientStream.Read(message, 0, 4096);
129: }
130: catch
131: {
132: //a socket error has occured
133: break;
134: }
135:
136: if (bytesRead == 0)
137: {
138: //the client has disconnected from the server
139: break;
140: }
141:
142: //message has successfully been received
143: var encoder = new ASCIIEncoding();
144: int read = bytesRead;
145: ReceivedMessage(_client, encoder.GetString(message, 0, read));
146: }
147:
148: tcpClient.Close();
149: }
150:
151: #endregion
152: }
1: internal class Client
2: {
3: private static void Main(string[] args)
4: {
5: Console.WriteLine("Press any key to start...");
6: Console.ReadKey(true);
7:
8: var client = new TcpClient();
9: client.StartConnect();
10: client.ReceivedMessage += (c, m) => Console.WriteLine("{0}:{1}", c.Client.AddressFamily, m);
11:
12: Console.WriteLine("Me: Hello server!");
13: client.SendMessage("Hello server!");
14:
15: Console.WriteLine("Press any key to stop...");
16: Console.ReadKey(true);
17: Environment.Exit(0);
18: }
19: }
1: public class TcpServer
2: {
3: #region Fields and Properties
4:
5: private readonly Thread _listenThread;
6: private readonly TcpListener _tcpListener;
7: public IPAddress IpAddress { get; set; }
8: private const int Port = 6666;
9:
10: #endregion
11:
12: #region Events
13:
14: #region Delegates
15:
16: public delegate void ReceivedMessageEventHandle(System.Net.Sockets.TcpClient client, string message);
17:
18: #endregion
19:
20: public event ReceivedMessageEventHandle ReceivedMessage;
21:
22: #endregion
23:
24: #region Constructors
25:
26: /// <summary>
27: /// Default constructor
28: /// </summary>
29: public TcpServer()
30: {
31: IpAddress = IPAddress.Any;
32: _tcpListener = new TcpListener(IpAddress, Port);
33: _listenThread = new Thread(ListenForClients);
34: }
35:
36: #endregion
37:
38: #region Start/Stop
39:
40: /// <summary>
41: /// Start listen client
42: /// </summary>
43: public void StartServer()
44: {
45: try
46: {
47: if (_listenThread.ThreadState != ThreadState.Running)
48: _listenThread.Start();
49: }
50: catch (Exception ex)
51: {
52: //Todo: Write log, or change return fuction is false
53: }
54: }
55:
56: /// <summary>
57: /// Stop listen client
58: /// </summary>
59: public void StopServer()
60: {
61: try
62: {
63: if (_listenThread.ThreadState == ThreadState.Running)
64: _listenThread.Abort();
65: }
66: catch (Exception ex)
67: {
68: //Todo: Write log, or change return fuction is false
69: }
70: }
71:
72: #endregion
73:
74: #region Listening
75:
76: /// <summary>
77: /// Listen all accept client and create thread for each client accepted
78: /// </summary>
79: private void ListenForClients()
80: {
81: _tcpListener.Start();
82: while (true)
83: {
84: try
85: {
86: //blocks until a client has connected to the server
87: System.Net.Sockets.TcpClient client = _tcpListener.AcceptTcpClient();
88: if (client.Connected)
89: {
90: //create a thread to handle communication
91: //with connected client
92: var clientThread = new Thread(HandleClientCommunication);
93: clientThread.Start(client);
94: }
95: }
96: catch (Exception ex)
97: {
98: //Todo: Write log exception
99: break;
100: }
101: }
102: }
103:
104: /// <summary>
105: /// Receive message from client and call event ReceivedMessage
106: /// </summary>
107: /// <param name="client"></param>
108: private void HandleClientCommunication(object client)
109: {
110: var tcpClient = (System.Net.Sockets.TcpClient)client;
111: NetworkStream clientStream = tcpClient.GetStream();
112:
113: var message = new byte[4096];
114:
115: while (true)
116: {
117: int bytesRead;
118:
119: try
120: {
121: //blocks until a client sends a message
122: bytesRead = clientStream.Read(message, 0, 4096);
123: }
124: catch (Exception ex)
125: {
126: //Todo: Write log exception
127: break;
128: }
129:
130: if (bytesRead == 0)
131: {
132: //the client has disconnected from the server
133: break;
134: }
135:
136: //message has successfully been received
137: var encoder = new ASCIIEncoding();
138: string receiveMessage = encoder.GetString(message, 0, bytesRead);
139:
140: // Event handle
141: if (ReceivedMessage != null)
142: ReceivedMessage(tcpClient, receiveMessage);
143: }
144:
145: tcpClient.Close();
146: }
147:
148: #endregion
149:
150: #region Send Message
151:
152: /// <summary>
153: /// Send message to client
154: /// </summary>
155: /// <param name="client"></param>
156: /// <param name="message"></param>
157: /// <returns></returns>
158: public bool SendMessage(System.Net.Sockets.TcpClient client, string message)
159: {
160: try
161: {
162: if (client != null && client.Connected)
163: {
164: NetworkStream clientStream = client.GetStream();
165:
166: var encoder = new ASCIIEncoding();
167: byte[] buffer = encoder.GetBytes(message);
168:
169: clientStream.Write(buffer, 0, buffer.Length);
170: clientStream.Flush();
171: return true;
172: }
173: return false;
174: }
175: catch (Exception ex)
176: {
177: //Todo: Write log exception
178: return false;
179: }
180: }
181:
182: #endregion
183: }
1: internal class Server
2: {
3: private static void Main(string[] args)
4: {
5: Console.WriteLine("Press any key to start...");
6: Console.ReadKey(true);
7:
8: var server = new TcpServer();
9: server.StartServer();
10: server.ReceivedMessage += (c, m) =>
11: {
12: Console.WriteLine("Client:{0}", m);
13:
14: Console.WriteLine("Me:Hello client!");
15: server.SendMessage(c, "Hello client!");
16: };
17:
18: Console.WriteLine("Press any key to stop...");
19: Console.ReadKey(true);
20: Environment.Exit(0);
21: }
22: }
Source: http://www.mediafire.com/?fc4fftap62g5qew
Video: http://www.youtube.com/watch?v=DZr9Fnb0WNI&feature=youtu.be
Yes, it run OK. See you late!
No comments:
Post a Comment