Socket服务端:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Net;
6: using System.Net.Sockets;
7: using System.Threading;
8:
9: namespace SocketServer
10: {
11: class Program
12: {
13: static bool ServiceStartFlag = false;
14: static Socket socket;
15: static Thread thread;
16:
17: static void Main(string[] args)
18: {
19: socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
20: IPHostEntry ieh = Dns.GetHostEntry("localhost");
21: IPAddress localServerIP = ieh.AddressList[1];
22: IPEndPoint localIPEndPoint = new IPEndPoint(localServerIP, 8080);
23:
24: socket.Bind(localIPEndPoint);
25: socket.Listen(600);
26:
27: thread = new Thread(new ThreadStart(AcceptClient));
28: thread.IsBackground = true;
29: thread.Start();
30:
31: Console.ReadLine();
32: }
33:
34: static void AcceptClient()
35: {
36: ServiceStartFlag = true;
37:
38: while (ServiceStartFlag)
39: {
40: try
41: {
42: Socket newSocket = socket.Accept();
43: string onemessge = "<cross-domain-policy><allow-access-from domain=\"" + "*" + "\" to-ports=\"8080\"/></cross-domain-policy>\0";
44:
45: byte[] tmpBytes = Encoding.UTF8.GetBytes(onemessge);
46: newSocket.Send(tmpBytes);
47:
48: Thread newThread = new Thread(new ParameterizedThreadStart(ReadMsg));
49: newThread.IsBackground = true;
50: object obj = newSocket;
51: newThread.Start(obj);
52: }
53: catch (SocketException ex)
54: {
55:
56:
57:
58: }
59: }
60: }
61:
62: static void ReadMsg(object obj)
63: {
64: Socket socket = (Socket)obj;
65:
66: byte[] byteMessage = null; ;
67:
68: while (ServiceStartFlag)
69: {
70: try
71: {
72: if (socket.Connected)
73: {
74:
75: byteMessage = new byte[1000];
76: int len = socket.Receive(byteMessage);
77: if (len > 0)
78: {
79: string sTime = DateTime.Now.ToShortTimeString();
80:
81: string msg = sTime + ":" + "Message from:";
82:
83: msg += socket.RemoteEndPoint.ToString() + Encoding.UTF8.GetString(byteMessage);
84: Console.WriteLine(msg);
85: byteMessage = null;
86:
87: byte[] tmpBytes = Encoding.UTF8.GetBytes("Sended Sucessed!\0");
88:
89: socket.Send(tmpBytes);
90: }
91:
92:
93: }
94: }
95: catch (SocketException ex)
96: {
97: Console.WriteLine(ex.Message);
98: }
99: }
100: }
101: }
102: }
103:
104:
.codearea { color: black; background-color: white; line-height: 18px; border: 1px solid rgb(79, 129, 189); margin: 0pt; width: auto ! important; overflow: auto; text-align: left; font-size: 12px; font-family: "Courier New","Consolas","Fixedsys","BitStream Vera Sans Mono",courier,monospace,serif; }.codearea pre { color: black; line-height: 18px; padding: 0pt 0pt 0pt 12px ! important; margin: 0em; background-color: rgb(255, 255, 255) ! important; }.linewrap pre { white-space: pre-wrap; word-wrap: break-word; }.codearea pre.alt { background-color: rgb(247, 247, 255) ! important; }.codearea .lnum { color: rgb(79, 129, 189); line-height: 18px; }
运行结果: