Socket 收发短信

Server(Receive Message)

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SocketServer
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>

        [MTAThread]
        static void Main()
        {
            SynchronousSocketListener.StartListening();
        }

    }
    public class SynchronousSocketListener
    {

        // Incoming data from the client.
        public static string data = null;

        public static void StartListening()
        {
            // Data buffer for incoming data.
            byte[] bytes = new Byte[1024];

            // Establish the local endpoint for the socket.
            // Dns.GetHostName returns the name of the
            // host running the application.
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 11000);

            // Create a TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                // Start listening for connections.
                while (true)
                {
                    Console.WriteLine( "Waiting for a connection…" );
                   // Program is suspended while waiting for an incoming connection.
                    Socket handler = listener.Accept();
                    data = null;
                    int bytesRec;

                    // An incoming connection needs to be processed.
                    while (true)
                    {
                        bytes = new byte[1024];
                        bytesRec = handler.Receive(bytes);
                        data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                        if (data.IndexOf( "<EOF>" ) > -1)
                        {
                            break;
                        }
                    }

                   // Show the data on the console.
                    Console.WriteLine( "Text received : {0}", data.Substring(0, bytesRec – 5) );

                    // Echo the data back to the client.
                    byte[] msg = Encoding.ASCII.GetBytes(data);

                    handler.Send(msg);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("nPress ENTER to continue…");
            Console.Read();

        }

    }
}

 

Client(Send Message)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace MessageClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sc, EventArgs e)
        {
            StartClient();
        }

        public void StartClient()
        {
            byte[] bytes = new byte[1024];
            try
            {
                IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("192.168.0.64"), 11000);

                // 创建 TCP/IP  socket.
                Socket sc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // 把socket连接到远程终端,并捕获例外
                try
                {
                    sc.Connect(remoteEP);

                    listBox1.Items.Add( "Socket connected to " + sc.RemoteEndPoint.ToString());

                   // 把string类编码成byte数组
                    byte[] msg = Encoding.ASCII.GetBytes(textBox1.Text + "<EOF>" );

                    // 通过socket发送数据
                    int bytesSent = sc.Send(msg);

                    // 从远程设备得到响应
                    int bytesRec = sc.Receive(bytes);
                    string recString = Encoding.ASCII.GetString(bytes, 0, bytesRec-5);
                    listBox1.Items.Add( "Message sent = " + recString);

                    // 释放socket
                    sc.Shutdown(SocketShutdown.Both);
                    sc.Close();

                }
                catch (ArgumentNullException ane)
                {
                    listBox1.Items.Add( "ArgumentNullException: " + ane.ToString());
                }
                catch (SocketException se)
                {
                    listBox1.Items.Add( "SocketException: " + se.ToString());
                }
                catch (Exception e)
                {
                    listBox1.Items.Add( "Unexpected exception: " + e.ToString());
                }

            }
            catch (Exception e)
            {
                listBox1.Items.Add(e.ToString());
            }
        }
    }
}

 

GUI:

MessagePicture

This entry was posted in Uncategorized. Bookmark the permalink.

One Response to Socket 收发短信

  1. 天雷 says:

    处理不了中文啊。。。请问如何处理中文?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s