Socket

来源:互联网 发布:天猫美工工资一般多少 编辑:程序博客网 时间:2024/06/06 17:09

左边框是用来显示聊天,连接信息的.右边列边是用来显示连接上来的客户端,只做了简单的显示.不难看出,好像是个简易聊天工具.

下面看看服务端代码吧:

Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net.Sockets;
using System.Collections;
using System.IO;
using System.Threading;

namespace WinAppSocket
{
    public partial class Form1 : Form
    {
        //Tcp连接监听者
        private TcpListener tcp = null;

        //Soket连接列表
        private List<ServerSocket> listMsg = new List<ServerSocket>();
        //Socket监听线程
        private Thread threadListener = null;

        public Form1()
        {
            InitializeComponent();
            TextBox.CheckForIllegalCrossThreadCalls = false;
            ListBox.CheckForIllegalCrossThreadCalls = false;
        }

        //开始连接
        private void btnConnection_Click(object sender, EventArgs e)
        {

            try
            {

                tcp = new TcpListener(new System.Net.IPAddress(new byte[] { 192, 168, 1, 200 }), 8909);
            }
            catch (Exception ex)
            {
                this.txtMsg.Text += ex.Message + "服务器启动连接失败!rn";
                return;
            }

            //启动监听
            tcp.Start();

            //创建监听线程
            threadListener = new Thread(new ThreadStart(ThreadListener));
            threadListener.Start();
            this.txtMsg.Text += "服务器等连接.!rn";
            btnConnection.Enabled = false;
        }

        //监听连接者
        private void ThreadListener()
        {
            while (true)
            {
                Socket sc = tcp.AcceptSocket();   
                if (sc != null)
                {
                    ServerSocket ssc = new ServerSocket(sc, this.txtMsg);
                    if (!listMsg.Contains(ssc))
                    {
                        listMsg.Add(ssc);
                        listSocket.Items.Add(ssc);
                        WaitCallback wcb = new WaitCallback(ssc.ReceiveMsg);                       
                        ThreadPool.QueueUserWorkItem(wcb);
                    }
                  
                }

            }
        }

        //发送数据
        private void button1_Click(object sender, EventArgs e)
        {
            ServerSocket sc = listSocket.SelectedItem as ServerSocket;
            if (sc != null && txtMsgSend.Text.Trim() != string.Empty)
            {
                sc.SendMsg(txtMsgSend.Text);
                txtMsgSend.Text = "";
            }
        }

    }
}

我还在服务端添加了一个ServerSoket,用来收发数据

 

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net.Sockets;
using System.Windows.Forms;
using System.IO;
using System.Data;

namespace WinAppSocket
{

    public class ServerSocket
    {
        private delegate void ShowMsg();//显示息信的委托

        //当前的Socket
        private Socket sc = null;

        //接收信息显示窗口
        private TextBox txtMsgContent = null;


        //定义一个显示消息的委托
        private ShowMsg msgShow = null;

        //接收到的的消息
        private string newMessage = string.Empty;

        //服务器商的Socket
        public ServerSocket(Socket sc, TextBox txtMsg)
        {
            this.sc = sc;
            txtMsgContent = txtMsg;
            msgShow = new ShowMsg(TextMsgShow);
        }

        //接收消息
        public void ReceiveMsg(object obj)
        {
            byte[] bytes;
            while (true)
            {
                bytes = new byte[1024];
                string result = "";
                int bytesRec = sc.Receive(bytes);
                if (bytesRec == 0)
                {
                    continue;
                }
                else
                {
                    result += Encoding.UTF8.GetString(bytes, 0, bytesRec);
                    newMessage = result;
                    if (newMessage.ToLower() == "griddata")
                    {
                          //发送griddata数据
                        SendMsg(GetString());
                    }
                    txtMsgContent.Invoke(msgShow);//显示消息
                }
            }
        }

        //显示收到的消息
        private void TextMsgShow()
        {
            this.txtMsgContent.Text += "服务器接收数据:" + newMessage;
            this.txtMsgContent.Text += "rn";
        }


        //发送消息
        public bool SendMsg(string msg)
        {
            //新建内存流
            MemoryStream ms = new MemoryStream();
            //二进制写入器
            BinaryWriter bs = new BinaryWriter(ms);
            bs.Write(msg.Trim());
            bs.Flush();
            int count = sc.Send(ms.ToArray());//发数数据


            this.txtMsgContent.Text += "向客户端发送数据:" + msg;
            this.txtMsgContent.Text += "rn";
            if (count > 0)
            {
                return true;
            }
            return false;
        }


        //为DataGrid准备的数据
        private string GetString()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add(new DataColumn("Name"));
            dt.Columns.Add(new DataColumn("Sex"));
            dt.Columns.Add(new DataColumn("Age"));
            dt.Columns.Add(new DataColumn("Address"));
            string name = string.Empty;
            //int age = 0;
            for (int i = 0; i < 10; i++)
            {
                dt.Rows.Add(new object[] { "dy" + i.ToString(), i % 2 == 0 ? "女" : "男", i * 10, "Socket" });
            }//添加十行数据

            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            return ds.GetXml();
        }


    }
}

至此服务端完成了!下面来看看客户端

 

Code
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/halo" minWidth="1024" minHeight="768">
    <s:layout>
        <s:BasicLayout/>
    </s:layout>

    <fx:Script>
        <![CDATA[
            import flash.net.*;
            import flash.utils.*;
           
            import mx.controls.Alert;
           
           
           
            //创奸一个Socket
            private var sc:Socket;
           
            private var isrequestDataGrid:Boolean=false;
           
           
            protected function btnConnection_clickHandler(event:MouseEvent):void
            {
                if(sc==null)
                {
                    sc=new Socket();
                }
                sc.connect("192.168.1.200",8909);//连接到服务器
                sc.addEventListener(Event.CONNECT,onResult);//连接成功
                sc.addEventListener(ProgressEvent.SOCKET_DATA, onData);//接收数据
                this.btnConnection.enabled=false;
               
            }
           
            private function onResult(event:Event):void
            {
                var baWrite:ByteArray =new ByteArray();
                baWrite.writeMultiByte("Flex来了","UTF-8");
                sc.writeBytes(baWrite);
                sc.flush();
                this.txtContent.text+="连接服务器成功!.n"
            }

           
           
            //发送数据
            protected function btnSend_clickHandler(event:MouseEvent):void
            {
                //新建缓冲区
                var biWrite:ByteArray =new ByteArray();
                //将数据写入缓冲区
                if(this.txtMsg.text.length>0)
                {
                    biWrite.writeMultiByte(this.txtMsg.text,"UTF-8");
                    sc.writeBytes(biWrite);
                    sc.flush();
                   
                    this.txtContent.text+="向服务发送数据:"+this.txtMsg.text+".n";
                }
                else
                {
                    mx.controls.Alert.show("发送信息不能为空呀!","警告");
                }
                this.txtMsg.text="";
           
            }
           
           
            //接收服务器发过来的数据           
            private function onData(event:ProgressEvent):void
            {
               
       
                   var len:int=sc.bytesAvailable;
                   if(len>0)
                   {
                       var biread:ByteArray =new ByteArray();
                       sc.readBytes(biread,0,sc.bytesAvailable);   
                       var str:String=biread.readMultiByte(len,"UTF-8");
                      
                       if(this.isrequestDataGrid)
                       {
                           this.isrequestDataGrid=false;
                           //处理 字符串的返回结果
                           var xml:XML=new XML(str.substr(str.indexOf("<")));
                           dgData.dataProvider=xml.children();
                          
                       }
                    this.txtContent.text+="服务器发来数据:"+str+"n";
                   }
            }


           
            //向服务器请求DataGrid数据
            protected function btnDataGrid_clickHandler(event:MouseEvent):void
            {
                    this.txtContent.text+="向服务器请求griddata数据.n";
                    var biWrite:ByteArray =new ByteArray();               
                    biWrite.writeMultiByte("griddata","UTF-8");
                    sc.writeBytes(biWrite);
                    sc.flush();
                    isrequestDataGrid=true;
                   
            }

        ]]>
    </fx:Script>

    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:Button x="29" y="10" label="连接" id="btnConnection" click="btnConnection_clickHandler(event)"/>
    <s:TextInput x="29" y="258" id="txtMsg"  width="366"/>
    <s:Button x="403" y="257" label="发送" id="btnSend" click="btnSend_clickHandler(event)"/>
    <s:TextArea x="29" y="49" width="437" id="txtContent" height="201"/>
    <s:Button x="29" y="303" label="请求DadataGrid数据" id="btnDataGrid" click="btnDataGrid_clickHandler(event)"/>
    <s:Panel x="28" y="338" width="426" height="247" id="pnlXml" title="返回的结果">
        <mx:DataGrid x="0" y="0" height="100%" width="100%" id="dgData">
            <mx:columns>
                <mx:DataGridColumn headerText="姓名" dataField="Name"/>
                <mx:DataGridColumn headerText="性别" dataField="Sex"/>
                <mx:DataGridColumn headerText="年龄" dataField="Age"/>
                <mx:DataGridColumn dataField="Address" headerText="请求类型"/>
            </mx:columns>
        </mx:DataGrid>
    </s:Panel>
</s:Application>


详细请参考:http://www.codesky.net/article/201211/179123.html

原创粉丝点击