相信技术的力量

我的力量
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

做了一个在线聊天器

Posted on 2008-11-19 20:01  三里人  阅读(277)  评论(0)    收藏  举报

今天发了半天的时间做了一个网络程序--在线聊天器,使用到底端口号,必须在防火墙开启(当时把瑞星防火墙关闭了,但是还有微软自带的没关,郁闷了半天才知道),这个聊天器比较低级,必须先启动服务器端,再启动客服端;关掉一个,必须关闭两个,然后再重新启动。代码如下:

客服端:

 

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;
using System.Net.Sockets;
using System.Threading;

namespace WinHello
{
    public partial class Form1 : Form
    {
        private Socket clientSocket;
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            startHello();
        }
        private void startHello()
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse("192.168.1.105");
            IPEndPoint ep = new IPEndPoint(ip, 6565);
            clientSocket.Connect(ep);

            Thread t = new Thread(new ThreadStart(clientThreadProc));
            t.Start();
        }
        private void clientThreadProc()
        {

            while (true)
            {
                while (clientSocket.Available == 0)
                {
                    Thread.Sleep(100);
                }
                byte[] bRecive = new byte[256];
                string reciveMsg = "";
                int n = clientSocket.Receive(bRecive, 0, clientSocket.Available, SocketFlags.None);
                if (n > 0)
                {
                    for (int i = 0; i < n; i += 2)
                    {
                        reciveMsg += (char)(bRecive[i + 1] * 256 + bRecive[i]);
                    }
                    txtList.Text += "Recive at " + DateTime.Now.ToString() + "\r\n \t" + reciveMsg + "\r\n";
                }
            }
        }
        /// <summary>
        /// 客户端发送信息按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {

                if (clientSocket.Connected == true)
                {
                    string msg = txtSend.Text;
                    byte[] bmsg = System.Text.Encoding.Unicode.GetBytes(msg);
                    int s = clientSocket.Send(bmsg, 0, bmsg.Length, SocketFlags.None);
                    txtList.Text += "Send at" + DateTime.Now.ToString() + "\r\n\t" + (char)13 + txtSend.Text + "\r\n";

                    //clientSocket.Shutdown(SocketShutdown.Both);
                    //clientSocket.Close();
                }
                else
                {
                    MessageBox.Show("连接不成功,请稍候重试!");
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        
       

    }
}

 

服务器端:、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、\\\\\\\\\\\\\\\\\\\\\\

 

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;
using System.Net.Sockets;
using System.Threading;

namespace WinServerHello
{
    public partial class Form1 : Form
    {
        Socket clientSocket;
        Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            serverOpen();
        }
        private void serverOpen()
        {
          
            IPAddress ip = IPAddress.Parse("192.168.1.105");
            IPEndPoint ep = new IPEndPoint(ip, 6565);
            serverSocket.Bind(ep);
            serverSocket.Listen(5);

            Thread t = new Thread(new ParameterizedThreadStart(serverThreadProc));
            t.Start(serverSocket );
        }
        public void serverThreadProc(object  _serverSocket)
        {
           
            Socket serverSocket = (Socket)_serverSocket;
            clientSocket = serverSocket.Accept();
            while (true)
            {
                try
                {
                   
                    if (clientSocket.Connected == true)
                    {
                        IPEndPoint cep = (IPEndPoint)clientSocket.RemoteEndPoint;
                        IPEndPoint sep = (IPEndPoint)serverSocket.LocalEndPoint;

                        while (clientSocket.Available == 0)
                        {
                            Thread.Sleep(100);
                        }
                        byte[] bRecive = new byte[256];
                        string receiveMsg = "";
                        int n = clientSocket.Receive(bRecive, 0, clientSocket.Available, SocketFlags.None);
                        if (n > 0)
                        {
                            for (int i = 0; i < n; i += 2)
                            {
                                receiveMsg += (char)(bRecive[i + 1] * 256 + bRecive[i]);
                            }
                            string s = "Recieve at " + DateTime.Now.ToShortTimeString() + "\r\n \t" + receiveMsg + "\r\n";
                            txtSList.Text  += s ;
                        }

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        private void btnSSend_Click(object sender, EventArgs e)
        {
            try
            {
                string sendMsg = txtSSend.Text;
                byte[] bMsg = new byte[256];
                bMsg = Encoding.Unicode.GetBytes(sendMsg);
                clientSocket.Send(bMsg, 0, bMsg.Length, SocketFlags.None);
                txtSList.Text += "Send at " + DateTime.Now.ToShortTimeString() + "\r\n \t" + sendMsg + "\r\n";

                //clientSocket.Shutdown(SocketShutdown.Both);
                //clientSocket.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}