Socket 编程示例(二)

利用晚上这点闲暇时间,写了一个Socket通信的小实例,该实例包含服务器端和客户端。其基本工作流程是:当服务器启动服务以后,客户端进行连接,如果连接成功,则用户可以在发送消息框中输入待发送的消息,然后点击“Send”按钮后向服务器发送消息,服务器在收到消息后立即向该客户端发送接收成功消息。其基本效果如图1.1和图1.2所示(注:下面两幅图于次日补上):

图1.1  服务器运行效果图

图1.2  客户端运行效果图

现将服务器和客户端部分代码贴出来,由于代码较简单,基本没有注释,并在此特别说明,该实例仅仅是一个简单的示例,其中的代码仍有进一步修改优化空间,同时亦欢迎各位朋友批评指正。
    服务器代码部分:
using System;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SocketServer
{
    public partial class frmServer : Form
    {
        private Thread m_serverThread;
        private Socket m_serverSocket;
        private string m_serverIP;
        private int m_serverPort;

public delegate void ReceiveMessageDelegate(Client client);
        ReceiveMessageDelegate receiveMessageDelegate;
        
        public frmServer()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

private void frmServer_Load(object sender, EventArgs e)
        {
            string[] addresses = GetLocalAddresses();
            cmbIP.Items.Clear();
            if (addresses.Length > 0)
            {
                for (int i = 0; i < addresses.Length; i++)
                {
                    cmbIP.Items.Add(addresses[i]);
                }
                cmbIP.Text = (string)cmbIP.Items[0];
            }

txtPort.Text = "8899";
        }

private void btnStart_Click(object sender, EventArgs e)
        {
            m_serverIP = cmbIP.Text;
            m_serverPort = Int32.Parse(txtPort.Text);

Start();
            btnStart.Enabled = false;
            btnStop.Enabled = true;
        }

private void btnStop_Click(object sender, EventArgs e)
        {
            Stop();
            btnStart.Enabled = true;
            btnStop.Enabled = false;
        }

/// <summary>
        /// 开始服务
        /// </summary>
        private void Start()
        {
            try
            {
                m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(m_serverIP), m_serverPort);
                m_serverSocket.Bind(localEndPoint);
                m_serverSocket.Listen(10);

m_serverThread = new Thread(new ThreadStart(ReceiveAccept));
                m_serverThread.Start();

this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Server started.");
            }
            catch (SocketException se)
            {
                throw new Exception(se.Message);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

/// <summary>
        /// 停止服务
        /// </summary>
        private void Stop()
        {
            try
            {
                m_serverThread.Abort(); // 线程终止
                m_serverSocket.Close(); // Socket Close

this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Server stoped.");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

private void ReceiveAccept()
        {
            while (true)
            {
                Client client = new Client();

try
                {
                    client.ClientSocket = m_serverSocket.Accept();
                    this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Client[" + client.ClientSocket.RemoteEndPoint.ToString() + "] connected.");

receiveMessageDelegate = new ReceiveMessageDelegate(ReceiveMessages);
                    receiveMessageDelegate.BeginInvoke(client, ReceiveMessagesCallback, "");
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }

private void ReceiveMessages(Client client)
        {
            while (true)
            {
                byte[] receiveBuffer = new byte[1024];

client.ClientSocket.Receive(receiveBuffer);

string strReceiveData = Encoding.Unicode.GetString(receiveBuffer);
                if (!string.IsNullOrEmpty(strReceiveData))
                {
                    this.AddRunningInfo(">> Receive data from [" + client.ClientSocket.RemoteEndPoint.ToString()+ "]:" + strReceiveData);
                    string strSendData = "OK. The content is:" + strReceiveData;
                    int sendBufferSize = Encoding.Unicode.GetByteCount(strSendData);
                    byte[] sendBuffer = new byte[sendBufferSize];
                    sendBuffer = Encoding.Unicode.GetBytes(strSendData);

client.ClientSocket.Send(sendBuffer);
                }
            }
        }

private void ReceiveMessagesCallback(IAsyncResult AR)
        {
            receiveMessageDelegate.EndInvoke(AR);
        }

/// <summary>
        /// 将运行信息加入显示列表
        /// </summary>
        private void AddRunningInfo(string message)
        {
            lstRunningInfo.BeginUpdate();
            lstRunningInfo.Items.Insert(0, message);

if (lstRunningInfo.Items.Count > 100)
            {
                lstRunningInfo.Items.RemoveAt(100);
            }

lstRunningInfo.EndUpdate();
        }

/// <summary>
        /// 获取本机地址列表
        /// </summary>
        public string[] GetLocalAddresses()
        {
            // 获取主机名
            string strHostName = Dns.GetHostName();

// 根据主机名进行查找
            IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);

string[] retval = new string[iphostentry.AddressList.Length];

int i = 0;
            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {
                retval[i] = ipaddress.ToString();
                i++;
            }
            return retval;
        } 
    }

/// <summary>
    /// 客户端会话信息类
    /// </summary>
    public class Client
    {
        Socket m_clientSocket;

public Client() { }

public Socket ClientSocket
        {
            get { return m_clientSocket; }
            set { this.m_clientSocket = value; }
        }
    }
}

客户端部分:
using System;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;

namespace SocketClient
{
    public partial class frmClient : Form
    {
        private Socket m_clientSocket;
        private byte[] m_receiveBuffer = new byte[1024];

public frmClient()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

private void frmClient_Load(object sender, EventArgs e)
        {
            txtIP.Text = "172.18.20.234";
            txtPort.Text = "8899";
        }

/// <summary>
        /// 连接服务器
        /// </summary>
        private void btnConnect_Click(object sender, EventArgs e)
        {
            string serverIP = txtIP.Text;
            int serverPort = Int32.Parse(txtPort.Text);

m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(serverIP),serverPort);

try
            {
                m_clientSocket.Connect(remoteEndPoint);
                if (m_clientSocket.Connected)
                {
                    m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);

btnConnect.Enabled = false;
                    btnDisconnect.Enabled = true;

this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Client connect server success.");
                }
            }
            catch (Exception)
            {
                this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Client connect server fail.");
                m_clientSocket = null;
            }
        }

/// <summary>
        /// 断开连接
        /// </summary>
        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            if (m_clientSocket != null)
            {
                m_clientSocket.Close();

btnConnect.Enabled = true;
                btnDisconnect.Enabled = false;
                btnSend.Enabled = false;

this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Client disconnected.");
            }
        }

/// <summary>
        /// 发送信息
        /// </summary>
        private void btnSend_Click(object sender, EventArgs e)
        {
            string strSendData = txtSend.Text;
            byte[] sendBuffer = new byte[1024];
            sendBuffer = Encoding.Unicode.GetBytes(strSendData);

if (m_clientSocket != null)
            {
                m_clientSocket.Send(sendBuffer);
            }
        }

private void ReceiveCallBack(IAsyncResult ar)
        {
            try
            {
                int REnd = m_clientSocket.EndReceive(ar);
                string strReceiveData = Encoding.Unicode.GetString(m_receiveBuffer, 0, REnd);
                this.HandleMessage(strReceiveData);
                m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

/// <summary>
        /// 处理接收到的数据
        /// </summary>
        private void HandleMessage(string message)
        {
            message = message.Replace("/0", "");
            if (!string.IsNullOrEmpty(message))
            {
                this.AddRunningInfo(">> Receive Data from server:" + message);
            }
        }

private void AddRunningInfo(string message)
        {
            lstRunningInfo.BeginUpdate();
            lstRunningInfo.Items.Insert(0, message);

if (lstRunningInfo.Items.Count > 100)
            {
                lstRunningInfo.Items.RemoveAt(100);
            }

lstRunningInfo.EndUpdate();
        }

private void txtSend_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtSend.Text) && m_clientSocket!=null)
            {
                btnSend.Enabled = true;
            }
            else
            {
                btnSend.Enabled = false;
            }
        }
    }
}

时间: 2024-10-15 21:42:25

Socket 编程示例(二)的相关文章

Windows Socket编程示例-TCP示例程序

前面一部分是介绍,后面有示例 1.网络中进程之间如何通信? 首要解决的问题是如何唯一标识一个进程,否则通信无从谈起!在本地可以通过进程PID来唯一标识一个进程,但是在网络中这是行不通的.其实TCP/IP协议族已经帮我们解决了这个问题,网络层的"ip地址"可以唯一标识网络中的主机,而传输层的"协议+端口"可以唯一标识主机中的应用程序(进程).这样利用三元组(ip地址,协议,端口)就可以标识网络的进程了,网络中的进程通信就可以利用这个标志与其它进程进行交互. 使用TCP

Linux socket编程示例(最简单的TCP和UDP两个例子)

一.socket编程 网络功能是Uinux/Linux的一个重要特点,有着悠久的历史,因此有一个非常固定的编程套路. 基于TCP的网络编程: 基于连接, 在交互过程中, 服务器和客户端要保持连接, 不能断开.重发一切出错数据.数据验证, 保证数据的正确性.完整性和顺序性, 缺点是消耗的资源比较大. 基于UDP的网络编程: 无连接协议, 在网络交互过程中不保持连接, 只需要在发送数据时连接一下, 不重发.验证数据.优点是资源消耗少, 数据的可靠性完整性 顺序性得不到保证. 二.编程步骤: 服务器:

Python 基础之socket编程(二)

Python 基础之socket编程(二) 昨天只是对socket编程做了简单的介绍,只是把socket通信的框架搭建起来,要对其中的功能进行进一步的扩充,就来看看今天的料哈! 一.基于tcp的套接字 1. tcp的服务端 ss = socket() #创建服务器套接字 ss.bind() #把地址绑定到套接字 ss.listen() #监听链接 inf_loop: #服务器无限循环 cs = ss.accept() #接受客户端链接 comm_loop: #通讯循环 cs.recv()/cs.

多线程Java Socket编程示例(转)

这篇做为学习孙卫琴<<Java网络编程精解>>的学习笔记吧.其中采用Java 5的ExecutorService来进行线程池的方式实现多线程,模拟客户端多用户向同一服务器端发送请求. 1.服务端 package sterning; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import

多线程Java Socket编程示例

package org.merit.test.socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; public class Hand

基于UDP协议的socket编程示例

客户端 import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; public class LoginClient { public static void main(Str

linux socket编程示例

#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <unistd.h> #include <stdlib.h> #include <assert.h> #include <stdio.h> #include <string.h> static bool

socket编程示例(多线程)

客户端代码如下: import java.io.*; import java.net.*; import java.util.Scanner; public class SimpleChatClient { BufferedReader reader; PrintWriter writer; Socket sock; public void go(){ System.out.println("客户端启动!"); setUpNetworking(); //发送数据到服务器 Scanner

socket编程(二)

TCP下粘包问题 两种情况下会发生粘包. 1.发送端需要等缓冲区满才发送出去,造成粘包(发送数据时间间隔很短,数据了很小,会合到一起,产生粘包) 发送方:AB #其实放在缓存里没发送 发送方:B #其实放在缓存里没发送 发送方:CD #缓存满了,发一波 接收方:ABBCD #及时从缓存里接收信息,我擦,发这是啥答案? 两同学传答案因粘包发生误会,后果严重 2.接收方不及时接收缓冲区的包,造成多个包接收(客户端发送了一段数据,服务端只收了一小部分,服务端下次再收的时候还是从缓冲区拿上次遗留的数据,