Socket 网络传输例子

创建socket服务器步骤

    指定端口实例化一个ServerSocket

    调用ServerSocket的accept()以在等待连接期间造成阻塞

     获取位于该层Socket的流以进行读写操作

     将数据封装成流

     对socket进行读写

     关闭打开的流



1   Socket 客户端代码

package com.epapandroid.service;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;

import android.R.integer;
import android.R.string;
import android.util.Base64;
 
 

     public class SocketClient {
    	 private static Socket client;
    	 int bufferSize = 1024; 

     private static SocketClient instance = null;
        
        public    SocketClient(String site, int port){
            try{
                client = new Socket(site,port);
                client.setSoTimeout(500000);
                System.out.println("Client is created! site:"+site+" port:"+port);
            }catch (UnknownHostException e){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
       public  static Boolean CheckSocketClient(String site, int port){
    	   try{
    		   Socket m_client = new Socket(site,port);
    		   m_client.close();
               return true;
           }catch (UnknownHostException e){
               e.printStackTrace();
           }catch (IOException e){
               e.printStackTrace();
           }
		return false;
       }
        
        public String sendMsg(String msg){
        	DataOutputStream out=null;
        	BufferedReader in=null;
            try{
            	 
            	msg=""+msg+"";
            	in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                
                out = new DataOutputStream(client.getOutputStream()); 
                 byte[] SendContent=msg.getBytes();
                 if(SendContent.length>bufferSize)
                 {
                	 int i=0;
                	 while(true)
                	 {
                		 if(i>SendContent.length) break;
                		 int sizelength=bufferSize;
                		 if(i+sizelength>SendContent.length) sizelength=SendContent.length-i;
                		 if(sizelength==0) break;
                		 byte[] tmpData=new byte[sizelength];
                		 System.arraycopy(SendContent, i, tmpData, 0, sizelength);
                		 out.write(tmpData);
                		 out.flush();
                		 i=i+sizelength;
                	 }
                	  
                	 
                 }
                 else {
					out.write(SendContent);
					out.flush();
				}
                
               
				String line = in.readLine();
                return line;
            }catch(IOException e){
                e.printStackTrace();
            }
            return "";
        }
        public String sendFileByBas64(String FilePath,String FileName)
        {
        	String result ="";
        	FileInputStream fis = null;
        	try {
        		// 将图片转为数据流。
			
				String uploadBuffer = "";
				try {
					fis = new FileInputStream(FilePath);

					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					byte[] buffer = new byte[1024];
					int count = 0;
					while ((count = fis.read(buffer)) >= 0) {
						baos.write(buffer, 0, count);
					}
					uploadBuffer = "UP|Upload_DefectPhoto|"+FileName+"|"+new String(Base64.encode(
							baos.toByteArray(), Base64.DEFAULT))+""; // 进行Base64编码
					 PrintWriter out = new PrintWriter(client.getOutputStream());
					 out.println(uploadBuffer);
					
					 Thread.sleep(3000);
				} catch (FileNotFoundException e) {

					e.printStackTrace();
				} catch (IOException e) {

					e.printStackTrace();
				}
				finally
				{
					 fis.close();
					 fis=null;
				}
				
			} catch (Exception e) {
				// TODO: handle exception
			}
        	return result;
        }
        /**
         * 发送文件
         * @param FilePath
         * @param FileName
         * @return
         */
        public String sendFile(String FilePath,String FileName)
        {
        	FileInputStream reader = null; 
        	 DataOutputStream out=null;
        	 byte[] buf = null;  
        	try {
        		BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                  out = new DataOutputStream(client.getOutputStream());
                File file=new File(FilePath);
                long filesize=file.length();
                file=null;
                out.writeBytes(""+"UP|DefectPhoto|"+filesize+"|"+FileName+"");
                
                out.flush();
                Thread.sleep(1000);
              
             // 1. 读取文件输入流  
                reader = new FileInputStream(FilePath);  
               
                // 2. 将文件内容写到Socket的输出流中  
                
               
               
                buf = new byte[bufferSize];  
                int read = 0;  
                int fileLength=0;
                // 将文件输入流 循环 读入 Socket的输出流中  
                while ((read = reader.read(buf, 0, buf.length)) != -1) {  
                    out.write(buf, 0, read); 
                     
                    fileLength=fileLength+buf.length;
                }  
                out.flush();
                Thread.sleep(3000);
                 
                out.writeBytes("");
                out.flush();
                Thread.sleep(1000);
				
			} catch (Exception e) {
				// TODO: handle exception
			}
        	finally {  
                try {  
                    // 结束对象  
                    buf = null;  
                   // out2.close();  
                    
                    reader.close();  
                    
                } catch (Exception e) {  
      
                }  
            }  
        	return "";
        }
        /**
         * 关闭输出
         */
        public void closeSocketOutPut()
        {
        	try {
				client.shutdownOutput();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        public void closeSocket(){
            try{
                client.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        // 接收服务器数据
        public   String readMessage() throws IOException
        {
            String str    =    "";
            try
            {
                BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
                str    =    br.readLine().replace("{", "").replace("}", "").replace("\"", "");
            }
            catch ( IOException e)
            {
                
            }
            
            return str;
            
        }

    }
    
   

 

2   服务端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;
using System.Windows.Forms;
using SerEPAPandroid.BAL;
using System.Diagnostics;
using System.Configuration;

namespace SocketUI
{
    public class ReceiveFiles
    {
        private static Thread threadWatch = null;
        private static Socket socketWatch = null;
        private static ListBox lstbxMsgView;//显示接受的文件等信息
        private static ListBox listbOnline;//显示用户连接列表

        private static Dictionary dict = new Dictionary();
       private static  ClsUpHandle clsUpHandle = new ClsUpHandle();
        private static IDictionary socketClientMsg = new Dictionary();

        public static void ExecCommand(string commandText)
        {
            Process p = new Process(); //实例一个Process类,启动一个独立进程  
            p.StartInfo.FileName = "cmd.exe"; //设定程序名  
            p.StartInfo.UseShellExecute = false; //关闭Shell的使用  
            p.StartInfo.RedirectStandardInput = true; //重定向标准输入  
            p.StartInfo.RedirectStandardOutput = true; //重定向标准输出  
            p.StartInfo.RedirectStandardError = true; //重定向错误输出  
            p.StartInfo.CreateNoWindow = true; // 设置不显示窗口  
            p.StartInfo.ErrorDialog = false;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.Start();
            p.StandardInput.WriteLine(@"" + commandText);

        }
        /// 
        /// 开始监听
        /// 
        /// 
        /// 
        public static void BeginListening(string localIp, string localPort, ListBox listbox, ListBox listboxOnline)
        {
            //基本参数初始化
            lstbxMsgView = listbox;
            listbOnline = listboxOnline;

            //创建服务端负责监听的套接字,参数(使用IPV4协议,使用流式连接,使用Tcp协议传输数据)
            socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //获取Ip地址对象
            IPAddress address = IPAddress.Parse(localIp);
            //创建包含Ip和port的网络节点对象
            IPEndPoint endpoint = new IPEndPoint(address, int.Parse(localPort));
            //将负责监听的套接字绑定到唯一的Ip和端口上
            socketWatch.Bind(endpoint);
            //设置监听队列的长度
            socketWatch.Listen(1000);
            //创建负责监听的线程,并传入监听方法
            threadWatch = new Thread(WatchConnecting);
            threadWatch.IsBackground = true;//设置为后台线程
            threadWatch.Start();//开始线程
            //ShowMgs("服务器启动监听成功");
            ShwMsgForView.ShwMsgforView(lstbxMsgView, "服务器启动监听成功");
        }

        /// 
        /// 连接客户端
        /// 
        private static void WatchConnecting()
        {
            while (true)//持续不断的监听客户端的请求
            {
                //开始监听 客户端连接请求,注意:Accept方法,会阻断当前的线程
                Socket connection = socketWatch.Accept();
                if (connection.Connected)
                {
                    //向列表控件中添加一个客户端的Ip和端口,作为发送时客户的唯一标识
                    ShwMsgForView.ShwMsgforView(listbOnline, connection.RemoteEndPoint.ToString());
                   // listbOnline.Items.Add(connection.RemoteEndPoint.ToString());
                    //将与客户端通信的套接字对象connection添加到键值对集合中,并以客户端Ip做为健
                    dict.Add(connection.RemoteEndPoint.ToString(), connection);
                    socketClientMsg.Add(connection, new StringBuilder());

                    //创建通信线程
                    ParameterizedThreadStart pts = new ParameterizedThreadStart(RecMsg);
                    Thread thradRecMsg = new Thread(pts);
                    thradRecMsg.IsBackground = true;
                    thradRecMsg.Start(connection);
                    ShwMsgForView.ShwMsgforView(lstbxMsgView, "客户端连接成功" + connection.RemoteEndPoint.ToString());
                }

            }
        }

        /// 
        /// 接收消息
        /// 
        /// 
        private static void RecMsg(object socketClientPara)
        {
            Socket socketClient = socketClientPara as Socket;

            while (true)
            {
                //定义一个接受用的缓存区(100M字节数组)
                //byte[] arrMsgRec = new byte[1024 * 1024 * 100];
                
                //将接收到的数据存入arrMsgRec数组,并返回真正接受到的数据的长度   
                if (socketClient.Connected)
                {
                    try
                    {
                        //因为终端每次发送文件的最大缓冲区是512字节,所以每次接收也是定义为512字节
                        byte[] buffer = new byte[1024];
                        int size = 0;
                        long len = 0;
                        StringBuilder revMsg = new StringBuilder();
                        string context = "";
                        bool isFile = false;
                        FileStream fs=null;
                        string FileName = "";
                        int fileSize = 0;
                        string SiteName="";
                        while ((size = socketClient.Receive(buffer, 0, buffer.Length, SocketFlags.None)) > 0)
                        {
                            len += size;
                            context = Encoding.UTF8.GetString(buffer, 0, size).Replace("\0", "").Replace("\n", "");
                            if(context.IndexOf("UP|DefectPhoto|")>-1)
                            {
                                 isFile = true;
                                if (!context.EndsWith(""))
                                { 
                                  //文件信息中有文件的数据。
                                    string tmpContent = context.Substring(0, context.IndexOf("") + 5);
                                    string[] tmpAry=tmpContent.Replace("", "").Replace("", "").Split('|');
                                     fileSize=int.Parse(tmpAry[2]);
                                     FileName = tmpAry[3];
                                    
                                    byte[] filebyte = Encoding.UTF8.GetBytes(tmpContent);
                                    size = size - filebyte.Length-1;
                                    byte[]tmpBuffer=new byte[size];
                                    Array.Copy(buffer, filebyte.Length , tmpBuffer, 0, size);
                                    buffer = tmpBuffer;
                                    context = Encoding.UTF8.GetString(buffer, 0, size).Replace("\0", "").Replace("\n", ""); 
                                }
                                else
                                {
                               
                                 // FileName = context.Replace("", "").Replace("", "").Split('|')[2];
                                    string[] tmpAry = context.Replace("", "").Replace("", "").Split('|');
                                    fileSize = int.Parse(tmpAry[2]);
                                    FileName = tmpAry[3];
                                }
                                string FilePath = "";
                                if (!clsUpHandle.CheckFileExists(FileName, ref FilePath))
                                {
                                    fs = new FileStream(FilePath, FileMode.Create);
                                }
                               // context = "";
                                //revMsg = new StringBuilder();
                            }
                            else if (context.IndexOf("UP|BaseDevicePhoto|") > -1)
                            {
                                #region 基础数据图片上传
                                isFile = true;
                                if (!context.EndsWith(""))
                                {
                                    //文件信息中有文件的数据。
                                    string tmpContent = context.Substring(0, context.IndexOf("") + 5);
                                    string[] tmpAry = tmpContent.Replace("", "").Replace("", "").Split('|');
                                    fileSize = int.Parse(tmpAry[2]);
                                    FileName = tmpAry[3];
                                    SiteName=tmpAry[4];

                                    byte[] filebyte = Encoding.UTF8.GetBytes(tmpContent);
                                    size = size - filebyte.Length - 1;
                                    byte[] tmpBuffer = new byte[size];
                                    Array.Copy(buffer, filebyte.Length, tmpBuffer, 0, size);
                                    buffer = tmpBuffer;
                                    context = Encoding.UTF8.GetString(buffer, 0, size).Replace("\0", "").Replace("\n", "");
                                }
                                else
                                {

                                    // FileName = context.Replace("", "").Replace("", "").Split('|')[2];
                                    string[] tmpAry = context.Replace("", "").Replace("", "").Split('|');
                                    fileSize = int.Parse(tmpAry[2]);
                                    FileName = tmpAry[3];
                                    SiteName=tmpAry[4];
                                }
                                string FilePath = "";
                                if (!clsUpHandle.CheckFileExistsByBaseUpload(SiteName, FileName, ref FilePath))
                                {
                                    fs = new FileStream(FilePath, FileMode.Create);
                                }
                                #endregion  
                            }

                            //判断有EOF结尾了就合并字符串。
                            if (context.EndsWith("") && !context.StartsWith(""))
                            {
                                revMsg.Append(context);
                            }
                            else if (context.EndsWith(""))
                            {
                                if (isFile)
                                {
                                    try
                                    {
                                        Log.Instance.WriteLog("客户端:" + socketClient.RemoteEndPoint + "  文件:"+FileName+" 上传成功!");
                                        if (fs != null)
                                        {
                                            fs.Flush();
                                            fs.Close();
                                            fs = null;
                                        }
                                    }
                                    catch(Exception e) {
                                        Log.Instance.WriteErrLog(e.Message);
                                    }
                                    isFile = false;
                                    context = "";
                                    buffer = new byte[1024];
                                    revMsg = new StringBuilder();
                                }
                            }
                            if (isFile && context.IndexOf("UP|DefectPhoto|") == -1 && context.IndexOf("UP|BaseDevicePhoto|") == -1)
                            {
                                if (fs != null)
                                {
                                    clsUpHandle.WriteDefectPhoto(fs, FileName, buffer,size);
                                }
                            }
                           
                            else if ((revMsg.ToString().StartsWith("") && revMsg.ToString().EndsWith("")) || (context.StartsWith("")   && context.EndsWith("")))
                            {
                                if (context.StartsWith("")  && context.EndsWith("") )
                                {
                                    revMsg.Append(context);
                                }
                                context = revMsg.ToString().Replace("", "").Replace("", "");
                                if (context.IndexOf("UP|") == 0)
                                {
                                    HandleUpData(socketClient, context);
                                    context = "";
                                    buffer = new byte[1024];
                                    revMsg = new StringBuilder();
                                }
                                else
                                {
                                    Response(socketClient, context);
                                    context = "";
                                    buffer = new byte[1024];
                                    revMsg = new StringBuilder();
                                }
                            }
                            else
                            {
                                revMsg.Append(context);
                            }
                        }
                        /*
                        if (isFile)
                        {
                            if (fs != null)
                            {
                                fs.Flush();
                                fs.Close();
                                context = "";
                                buffer = new byte[1024];
                                revMsg = new StringBuilder();
                            }
                        }
                        else
                        {
                            context = revMsg.ToString().Replace("", "").Replace("", "");
                            if (context.IndexOf("UP|") == 0)
                            {
                                HandleUpData(socketClient, context);
                            }
                            else
                            {
                                Response(socketClient, context);
                            }
                        }*/
                        //创建文件流,然后让文件流来根据路径创建一个文件
                       // FileStream fs = new FileStream(fileName, FileMode.Create);
                        //从终端不停的接受数据,然后写入文件里面,只到接受到的数据为0为止,则中断连接
 
                       // fs.Flush();
                      
                            ShwMsgForView.ShwMsgforView(lstbxMsgView, socketClient.RemoteEndPoint + "断开连接");
                            dict.Remove(socketClient.RemoteEndPoint.ToString());
                            ShwMsgForView.RemoveMsgforView(listbOnline,socketClient.RemoteEndPoint.ToString());
                            
                           socketClient.Close();
                            break;
                        
                        
                    }
                    catch(Exception e)
                    {
                        Log.Instance.WriteErrLog(socketClient.RemoteEndPoint.ToString()+"  "+e.Message);
                        ShwMsgForView.ShwMsgforView(lstbxMsgView, socketClient.RemoteEndPoint + "下线了");
                        dict.Remove(socketClient.RemoteEndPoint.ToString());
                        ShwMsgForView.RemoveMsgforView(listbOnline, socketClient.RemoteEndPoint.ToString());
                        break;
                    }
                }
                else
                {
                    try
                    {
                        ShwMsgForView.ShwMsgforView(lstbxMsgView, socketClient.RemoteEndPoint + "断开连接");
                        dict.Remove(socketClient.RemoteEndPoint.ToString());
                        ShwMsgForView.RemoveMsgforView(listbOnline, socketClient.RemoteEndPoint.ToString());

                        socketClient.Close();
                    }
                    catch
                    { }
                    break;
                }
            }
        }

        /// 
        /// 处理上传数据。
        /// 
        /// UP|方法|参数
        private static void HandleUpData(Socket client, string context)
        {
           
            string result = "";
            try
            {
                string[] aryTmp = context.Split('|');

                switch (aryTmp[1])
                {
                    case "Upload_DayPlanAndRange":
                        result = clsUpHandle.Upload_DayPlanAndRange(aryTmp[2]);
                        break;
                    case "UploadDevInfoAndStatue":
                        result = clsUpHandle.UploadDevInfoAndStatue(aryTmp[2], aryTmp[3], aryTmp[4], aryTmp[5]);
                        break;
                    case "UploadDefectInfo":
                        result = clsUpHandle.UploadDefectInfo(aryTmp[2], aryTmp[3], aryTmp[4], aryTmp[5]);
                        break;
                    case "UploadGpsLocus":
                        result = clsUpHandle.UploadGpsLocus(aryTmp[2]);
                        break;
                    case "Upload_DefectPhoto":
                        result = clsUpHandle.SaveDefectPhoto(aryTmp[2], aryTmp[3]);
                        break;
                    case "UploadCollectBaseData":
                        //上传采集基础数据
                      
                        result = clsUpHandle.UploadCollectBaseData(aryTmp[2]);
                        break;

                }
                Log.Instance.WriteLog("上传的数据为:" + context);
                ShwMsgForView.ShwMsgforView(lstbxMsgView, "上传的数据为:" + context);

            }
            catch(Exception e)
            {
                Log.Instance.WriteErrLog(e.Message + "\r\n 内容:"+context);
                result = "";
            }
            byte[] buf = Encoding.UTF8.GetBytes(result + "\n");
            client.Send(buf);

            
        }
        private  static void Response(Socket client, string context)
        {

            ClsBaseDataDown clsBaseData = new ClsBaseDataDown();
            if (client == null)
            {
                return;
            }
            try
            {
                string[] aryTmp = context.Split('|');
                string result = "";
                switch (aryTmp[0])
                {
                    #region 数据下载
                    case "DefectType":
                        result = clsBaseData.GetDefectType();

                        break;
                    case "DefectReason":
                        result = clsBaseData.GetDefectReason();
                        break;
                    case "Site":
                        //Site|deptcode
                        result = clsBaseData.GetSite(aryTmp[1]);
                        break;
                    case "AllSite":
                        result = clsBaseData.GetAllSite();
                        break;
                    case "Updown":
                        result = clsBaseData.GetUpdown();
                        break;
                    case "Devclass":
                        result = clsBaseData.GetDevclass();
                        break;
                    case "UserAndEmp":
                        //UserAndEmp|deptcode
                        result = clsBaseData.GetUserAndEmp(aryTmp[1]);
                        break;

                    case "AllUserAndEmp":
                        result = clsBaseData.GetAllUserAndEmp();
                        break;
                    case "DayPlan":
                        //DayPlan|deptcode
                        result = clsBaseData.GetDayPlan(aryTmp[1]);
                        break;
                    case "PlanAndRange":
                        //PlanAndRange|DayPlanID|DAYRANGEID
                        result = clsBaseData.GetDayPlanByDayPlanID(int.Parse(aryTmp[1]), int.Parse(aryTmp[2]));
                        break;
                    case "DevStatue":
                        //DevStatue|DAYRANGEID
                        result = clsBaseData.GetDevStatue(int.Parse(aryTmp[1]));
                        break;
                    case "Device":
                        //Device|DeptCode|DayRangeID
                        result = clsBaseData.GetDevice(aryTmp[1], int.Parse(aryTmp[2]));
                        break;
                    case "Devices":
                        //Devices|DeptCode|DayRangeID
                        result = clsBaseData.GetDevices(aryTmp[1], int.Parse(aryTmp[2]));
                        break;
                    case "Department":
                        result = clsBaseData.GetDepartment();
                        break;
                    #endregion



                }
                byte[] buf = Encoding.UTF8.GetBytes(result + "\n");
                client.Send(buf);
               // client.Send(buf);

                Log.Instance.WriteLog("发送的数据为:" + result);
                ShwMsgForView.ShwMsgforView(lstbxMsgView, "发送的数据为:" + result);

            }
            catch (Exception ex)
            {
                Log.Instance.WriteErrLog(ex.Message);
                ShwMsgForView.ShwMsgforView(lstbxMsgView, string.Format("接收的数据出错:\r\n{0}", ex.ToString()));
                
            }



        }

        /// 
        /// 关闭连接
        /// 
        public static void CloseTcpSocket()
        {
            dict.Clear();
            listbOnline.Items.Clear();
            threadWatch.Abort();
            socketWatch.Close();
            ShwMsgForView.ShwMsgforView(lstbxMsgView, "服务器关闭监听");
        }
    }
}
 
  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
using SerEPAPandroid.BAL;

namespace SocketUI
{
    public class SocketClient
    {
        private static Thread threadWatch = null;
        private static Socket socketWatch = null;
        private static ListBox lstbxMsgView;//显示接受的文件等信息
        private static ListBox listbOnline;//显示用户连接列表

        private static Socket s;                                         //定义Socket对象                  
        public static  NetworkStream ns;                                //网络流
        public static StreamReader sr;                                 //流读取 
        public static StreamWriter sw;                                 //流写入
        private static ClsUpHandle clsUpHandle = new ClsUpHandle();
        public static void ExecCommand(string commandText)
        {
            Process p = new Process(); //实例一个Process类,启动一个独立进程  
            p.StartInfo.FileName = "cmd.exe"; //设定程序名  
            p.StartInfo.UseShellExecute = false; //关闭Shell的使用  
            p.StartInfo.RedirectStandardInput = true; //重定向标准输入  
            p.StartInfo.RedirectStandardOutput = true; //重定向标准输出  
            p.StartInfo.RedirectStandardError = true; //重定向错误输出  
            p.StartInfo.CreateNoWindow = true; // 设置不显示窗口  
            p.StartInfo.ErrorDialog = false;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.Start();
            p.StandardInput.WriteLine(@"" + commandText);

        }
         /// 
        /// 开始监听
        /// 
        /// 
        /// 
        public static void BeginListening(string localIp, string localPort, ListBox listbox, ListBox listboxOnline)
        {
           
            try
            {
                //创建服务端负责监听的套接字,参数(使用IPV4协议,使用流式连接,使用Tcp协议传输数据)
                socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //获取Ip地址对象
                IPAddress address = IPAddress.Parse(localIp);
                //创建包含Ip和port的网络节点对象
                IPEndPoint endpoint = new IPEndPoint(address, int.Parse(localPort));
                //将负责监听的套接字绑定到唯一的Ip和端口上
                socketWatch.Bind(endpoint);
                //设置监听队列的长度
                socketWatch.Listen(1000);
                 
                ShwMsgForView.ShwMsgforView(lstbxMsgView, "服务器启动监听成功");
                 
                //创建通信线程
                ParameterizedThreadStart pts = new ParameterizedThreadStart(Communication);
                Thread thradRecMsg = new Thread(pts);
                thradRecMsg.IsBackground = true;
                thradRecMsg.Start(socketWatch);

            }
            catch
            {

            }
            finally
            {
                socketWatch.Close();  
            }
        }
        /// 
        /// 接收消息
        /// 
        /// 
        private static void Communication(object socketClientPara)
        {
            Socket socketClient = socketClientPara as Socket;

            try
            {
                while (true)
                {

                    //因为终端每次发送文件的最大缓冲区是512字节,所以每次接收也是定义为512字节
                    byte[] buffer = new byte[1024];
                    int size = 0;
                    long len = 0;
                    StringBuilder revMsg = new StringBuilder();
                    string context = "";
                    bool isFile = false;
                    FileStream fs = null;
                    string FileName = "";
                    while ((size = socketClient.Receive(buffer, 0, buffer.Length, SocketFlags.None)) > 0)
                    {
                        len += size;
                        context = Encoding.UTF8.GetString(buffer, 0, buffer.Length).Replace("\n", "");
                        if (context.IndexOf("UP|DefectPhoto|") > -1)
                        {
                            isFile = true;
                            FileName = context.Replace("", "").Replace("", "").Split('|')[2];
                            string FilePath = "";
                            if (!clsUpHandle.CheckFileExists(FileName, ref FilePath))
                            {
                                fs = new FileStream(FilePath, FileMode.Create);
                            }
                        }
                        if (isFile && context.IndexOf("UP|DefectPhoto|") == -1)
                        {
                            if (fs != null)
                            {
                                clsUpHandle.WriteDefectPhoto(fs, FileName, buffer,size);
                            }
                        }
                        else
                        {
                            revMsg.Append(context);
                        }
                    }
                    if (isFile)
                    {
                        if (fs != null)
                        {
                            fs.Flush();
                            fs.Close();
                        }
                    }
                    else
                    {
                        context = revMsg.ToString().Replace("", "").Replace("", "");
                        if (context.IndexOf("UP|") == 0)
                        {
                            HandleUpData(socketClient, context);
                        }
                        else
                        {
                            Response(socketClient, context);
                        }
                    }
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);                  //捕获异常
            }
        }
        /// 
        /// 处理上传数据。
        /// 
        /// UP|方法|参数
        private static void HandleUpData(Socket client, string context)
        {

            string result = "";
            try
            {
                string[] aryTmp = context.Split('|');

                switch (aryTmp[1])
                {
                    case "Upload_DayPlanAndRange":
                        result = clsUpHandle.Upload_DayPlanAndRange(aryTmp[2]);
                        break;
                    case "UploadDevInfoAndStatue":
                        result = clsUpHandle.UploadDevInfoAndStatue(aryTmp[2], aryTmp[3], aryTmp[4], aryTmp[5]);
                        break;
                    case "UploadDefectInfo":
                        result = clsUpHandle.UploadDefectInfo(aryTmp[2], aryTmp[3], aryTmp[4], aryTmp[5]);
                        break;
                    case "UploadGpsLocus":
                        result = clsUpHandle.UploadGpsLocus(aryTmp[2]);
                        break;
                    case "DefectPhoto":
                        result = clsUpHandle.SaveDefectPhoto(aryTmp[2], aryTmp[3]);
                        break;
                }

            }
            catch
            {
                result = "";
            }
            byte[] buf = Encoding.UTF8.GetBytes(result + "\n");
            client.Send(buf);


        }

        private static void Response(Socket client, string context)
        {

            ClsBaseDataDown clsBaseData = new ClsBaseDataDown();
            if (client == null)
            {
                return;
            }
            try
            {
                string[] aryTmp = context.Split('|');
                string result = "";
                switch (aryTmp[0])
                {
                    #region 数据下载
                    case "DefectType":
                        result = clsBaseData.GetDefectType();
                        break;
                    case "DefectReason":
                        result = clsBaseData.GetDefectReason();
                        break;
                    case "Site":
                        //Site|deptcode
                        result = clsBaseData.GetSite(aryTmp[1]);
                        break;
                    case "Updown":
                        result = clsBaseData.GetUpdown();
                        break;
                    case "Devclass":
                        result = clsBaseData.GetDevclass();
                        break;
                    case "UserAndEmp":
                        //UserAndEmp|deptcode
                        result = clsBaseData.GetUserAndEmp(aryTmp[1]);
                        break;
                    case "DayPlan":
                        //DayPlan|deptcode
                        result = clsBaseData.GetDayPlan(aryTmp[1]);
                        break;
                    case "PlanAndRange":
                        //PlanAndRange|DayPlanID|DAYRANGEID
                        result = clsBaseData.GetDayPlanByDayPlanID(int.Parse(aryTmp[1]), int.Parse(aryTmp[2]));
                        break;
                    case "DevStatue":
                        //DevStatue|DAYRANGEID
                        result = clsBaseData.GetDevStatue(int.Parse(aryTmp[1]));
                        break;
                    case "Device":
                        //Device|DeptCode|DayRangeID
                        result = clsBaseData.GetDevice(aryTmp[1], int.Parse(aryTmp[2]));
                        break;
                    case "Devices":
                        //Devices|DeptCode|DayRangeID
                        result = clsBaseData.GetDevices(aryTmp[1], int.Parse(aryTmp[2]));
                        break;
                    #endregion



                }
                byte[] buf = Encoding.UTF8.GetBytes(result + "\n");
                client.Send(buf);
                // client.Send(buf);


                ShwMsgForView.ShwMsgforView(lstbxMsgView, "发送的数据为:" + result);

            }
            catch (Exception ex)
            {
                ShwMsgForView.ShwMsgforView(lstbxMsgView, string.Format("接收的数据出错:\r\n{0}", ex.ToString()));

            }



        }

    }
}


 
  

你可能感兴趣的:(Socket 网络传输例子)