C# Socket编程
1 //Socket基本编程
2 //服务端:
3
4 using System.Net;
5
6 using System.Net.Sockets;
7
8 using System.Text;
9
10 using System.Threading;
11
12
13
14 Thread mythread ;
15
16 Socket socket;
17
18 // 清理所有正在使用的资源。
19
20 protected override void Dispose( bool disposing )
21
22 {
23
24 try
25
26 {
27
28 socket.Close();//释放资源
29
30 mythread.Abort ( ) ;//中止线程
31
32 }
33
34 catch{ }
35
36
37
38 if( disposing )
39
40 {
41
42 if (components != null)
43
44 {
45
46 components.Dispose();
47
48 }
49
50 }
51
52 base.Dispose( disposing );
53
54 }
55
56 public static IPAddress GetServerIP()
57
58 {
59
60 IPHostEntry ieh=Dns.GetHostByName(Dns.GetHostName());
61
62 return ieh.AddressList[0];
63
64 }
65
66 private void BeginListen()
67
68 {
69
70 IPAddress ServerIp=GetServerIP();
71
72 IPEndPoint iep=new IPEndPoint(ServerIp,8000);
73
74 socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
75
76
77
78 byte[] byteMessage=new byte[100];
79
80 this.label1.Text=iep.ToString();
81
82 socket.Bind(iep);
83
84 // do
85
86 while(true)
87
88 {
89
90 try
91
92 {
93
94 socket.Listen(5);
95
96 Socket newSocket=socket.Accept();
97
98 newSocket.Receive(byteMessage);
99
100
101
102 string sTime = DateTime.Now.ToShortTimeString ( ) ;
103
104 string msg=sTime+":"+"Message from:";
105
106 msg+=newSocket.RemoteEndPoint.ToString()+Encoding.Default.GetString(byteMessage);
107
108 this.listBox1.Items.Add(msg);
109
110
111
112 }
113
114 catch(SocketException ex)
115
116 {
117
118 this.label1.Text+=ex.ToString();
119
120 }
121
122 }
123
124 // while(byteMessage!=null);
125
126 }
127
128 //开始监听
129
130 private void button1_Click(object sender, System.EventArgs e)
131
132 {
133
134 try
135
136 {
137
138 mythread = new Thread(new ThreadStart(BeginListen));
139
140 mythread.Start();
141
142
143
144 }
145
146 catch(System.Exception er)
147
148 {
149
150 MessageBox.Show(er.Message,"完成",MessageBoxButtons.OK,MessageBoxIcon.Stop);
151
152 }
153
154 }
155
156
157
158
159
160 //客户端:
161
162
163
164 using System.Net;
165
166 using System.Net.Sockets;
167
168 using System.Text;
169
170
171
172 private void button1_Click(object sender, System.EventArgs e)
173
174 {
175
176 BeginSend();
177
178 }
179
180 private void BeginSend()
181
182 {
183
184 string ip=this.txtip.Text;
185
186 string port=this.txtport.Text;
187
188
189
190 IPAddress serverIp=IPAddress.Parse(ip);
191
192 int serverPort=Convert.ToInt32(port);
193
194 IPEndPoint iep=new IPEndPoint(serverIp,serverPort);
195
196 byte[] byteMessage;
197
198 // do
199
200 // {
201
202 Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
203
204 socket.Connect(iep);
205
206
207
208 byteMessage=Encoding.ASCII.GetBytes(textBox1.Text);
209
210 socket.Send(byteMessage);
211
212 socket.Shutdown(SocketShutdown.Both);
213
214 socket.Close();
215
216 // }
217
218 // while(byteMessage!=null);
219
220 }
221
222
基于TCP协议的发送和接收端
TCP协议的接收端
1
2
3 using System.Net.Sockets ; //使用到TcpListen类
4
5 using System.Threading ; //使用到线程
6
7 using System.IO ; //使用到StreamReader类
8
9
10
11 int port = 8000; //定义侦听端口号
12
13 private Thread thThreadRead; //创建线程,用以侦听端口号,接收信息
14
15 private TcpListener tlTcpListen; //侦听端口号
16
17 private bool blistener = true; //设定标示位,判断侦听状态
18
19 private NetworkStream nsStream; //创建接收的基本数据流
20
21 private StreamReader srRead;
22
23 private System.Windows.Forms.StatusBar statusBar1;
24
25 private System.Windows.Forms.Button button1;
26
27 private System.Windows.Forms.ListBox listBox1; //从网络基础数据流中读取数据
28
29 private TcpClient tcClient ;
30
31
32
33 private void Listen ( )
34
35 {
36
37 try
38
39 {
40
41 tlTcpListen = new TcpListener ( port ) ; //以8000端口号来初始化TcpListener实例
42
43 tlTcpListen.Start ( ) ; //开始监听
44
45 statusBar1.Text = "正在监听" ;
46
47 tcClient = tlTcpListen.AcceptTcpClient ( ) ; //通过TCP连接请求
48
49 nsStream = tcClient.GetStream ( ) ; //获取用以发送、接收数据的网络基础数据流
50
51 srRead=new StreamReader(nsStream);//以得到的网络基础数据流来初始化StreamReader实例
52
53 statusBar1.Text = "已经连接!";
54
55
56
57 while( blistener ) //循环侦听
58
59 {
60
61 string sMessage = srRead.ReadLine();//从网络基础数据流中读取一行数据
62
63 if ( sMessage == "STOP" ) //判断是否为断开TCP连接控制码
64
65 {
66
67 tlTcpListen.Stop(); //关闭侦听
68
69 nsStream.Close(); //释放资源
70
71 srRead.Close();
72
73 statusBar1.Text = "连接已经关闭!" ;
74
75 thThreadRead.Abort(); //中止线程
76
77 return;
78
79 }
80
81
82
83 string sTime = DateTime.Now.ToShortTimeString ( ) ; //获取接收数据时的时间
84
85 listBox1.Items.Add ( sTime + " " + sMessage ) ;
86
87 }
88
89 }
90
91 catch ( System.Security.SecurityException )
92
93 {
94
95 MessageBox.Show ( "侦听失败!" , "错误" ) ;
96
97 }
98
99 }
100
101 //开始监听
102
103 private void button1_Click(object sender, System.EventArgs e)
104
105 {
106
107 thThreadRead = new Thread ( new ThreadStart ( Listen ) );
108
109 thThreadRead.Start();//启动线程
110
111 button1.Enabled=false;
112
113 }
114
115 // 清理所有正在使用的资源。
116
117 protected override void Dispose( bool disposing )
118
119 {
120
121 try
122
123 {
124
125 tlTcpListen.Stop(); //关闭侦听
126
127 nsStream.Close();
128
129 srRead.Close();//释放资源
130
131 thThreadRead.Abort();//中止线程
132
133 }
134
135 catch{}
136
137
138
139 if( disposing )
140
141 {
142
143 if (components != null)
144
145 {
146
147 components.Dispose();
148
149 }
150
151 }
152
153 base.Dispose( disposing );
154
155 }
TCP协议的发送端
1 using System.Net.Sockets; //使用到TcpListen类
2
3 using System.Threading; //使用到线程
4
5 using System.IO; //使用到StreamWriter类
6
7 using System.Net; //使用IPAddress类、IPHostEntry类等
8
9
10
11 private StreamWriter swWriter; //用以向网络基础数据流传送数据
12
13 private NetworkStream nsStream; //创建发送数据的网络基础数据流
14
15 private TcpClient tcpClient;
16
17 private System.Windows.Forms.Button button1;
18
19 private System.Windows.Forms.TextBox textBox1;
20
21 private System.Windows.Forms.Button button2;
22
23 private System.Windows.Forms.TextBox textBox2;
24
25 private System.Windows.Forms.StatusBar statusBar1;
26
27 private System.Windows.Forms.Label label1;
28
29 private System.Windows.Forms.Label label2; //通过它实现向远程主机提出TCP连接申请
30
31 private bool tcpConnect = false; //定义标识符,用以表示TCP连接是否建立
32
33
34
35 //连接
36
37 private void button1_Click(object sender, System.EventArgs e)
38
39 {
40
41 IPAddress ipRemote ;
42
43 try
44
45 {
46
47 ipRemote = IPAddress.Parse ( textBox1.Text ) ;
48
49 }
50
51 catch //判断给定的IP地址的合法性
52
53 {
54
55 MessageBox.Show ( "输入的IP地址不合法!" , "错误提示!" ) ;
56
57 return ;
58
59 }
60
61
62
63 IPHostEntry ipHost ;
64
65 try
66
67 {
68
69 ipHost = Dns.Resolve ( textBox1.Text ) ;
70
71 }
72
73 catch //判断IP地址对应主机是否在线
74
75 {
76
77 MessageBox.Show ("远程主机不在线!" , "错误提示!" ) ;
78
79 return ;
80
81 }
82
83
84
85 string sHostName = ipHost.HostName ;
86
87 try
88
89 {
90
91 TcpClient tcpClient = new TcpClient(sHostName,8000);//对远程主机的8000端口提出TCP连接申请
92
93 nsStream = tcpClient.GetStream();//通过申请,并获取传送数据的网络基础数据流
94
95 swWriter = new StreamWriter(nsStream);//使用获取的网络基础数据流来初始化StreamWriter实例
96
97 button1.Enabled = false ;
98
99 button2.Enabled = true ;
100
101 tcpConnect = true ;
102
103 statusBar1.Text = "已经连接!" ;
104
105 }
106
107 catch
108
109 {
110
111 MessageBox.Show ( "无法和远程主机8000端口建立连接!" , "错误提示!" ) ;
112
113 return ;
114
115 }
116
117 }
118
119
120
121 //发送
122
123 private void button2_Click(object sender, System.EventArgs e)
124
125 {
126
127 if (textBox2.Text !="")
128
129 {
130
131 swWriter.WriteLine(textBox2.Text);//刷新当前数据流中的数据
132
133 swWriter.Flush();
134
135 }
136
137 else
138
139 {
140
141 MessageBox.Show("发送信息不能为空!","错误提示!");
142
143 }
144
145 }
146
147 // 清理所有正在使用的资源。
148
149 protected override void Dispose( bool disposing )
150
151 {
152
153 if ( tcpConnect )
154
155 {
156
157 swWriter.WriteLine ( "STOP" ) ; //发送控制码
158
159 swWriter.Flush (); //刷新当前数据流中的数据
160
161 nsStream.Close (); //清除资源
162
163 swWriter.Close ();
164
165 }
166
167 if( disposing )
168
169 {
170
171 if (components != null)
172
173 {
174
175 components.Dispose();
176
177 }
178
179 }
180
181 base.Dispose( disposing );
182
183 }