1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Net.Sockets;
5 using System.Net;
6 using System.IO;
7
8 namespace ConsoleApplication1
9 {
10 class Program
11 {
12 static void Main(string[] args)
13 {
14 // 1.创建套节字
15 Socket sListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
16
17 // 2.填充IP
18 IPAddress ip = IPAddress.Parse("127.0.0.1");
19 IPEndPoint ipe = new IPEndPoint(ip, 4321);
20
21 // 3.绑定
22 sListen.Bind(ipe);
23
24 // 4.监听
25 Console.WriteLine("服务正在监听...");
26 sListen.Listen(2);
27
28 // 5.循环接受客户的连接请求
29 while (true)
30 {
31 Socket clientSocket;
32 try
33 {
34 clientSocket = sListen.Accept();
35 }
36 catch
37 {
38 throw;
39 }
40
41 // 向客户端发送数据
42 //clientSocket.Send(Encoding.Unicode.GetBytes("我是服务器, 你好呀!!!!"));
43
44 // 发送文件
45 byte[] buffer = ReadImageFile("1.jpg");
46 clientSocket.Send(buffer, buffer.Length, SocketFlags.None);
47 Console.WriteLine("发送成功!");
48 }
49 }
50
51 private static byte[] ReadImageFile(string img)52 {53 FileInfo fileInfo = new FileInfo(img);54 byte[] buf = new byte[fileInfo.Length];55 FileStream fs = new FileStream(img, FileMode.Open, FileAccess.Read);56 fs.Read(buf, 0, buf.Length);57 fs.Close();58 //fileInfo.Delete();59 GC.ReRegisterForFinalize(fileInfo);60 GC.ReRegisterForFinalize(fs);61 return buf;62 }63 64 }65 }66