我需要创建客户端服务器应用程序,其中客户端使用端口A来请求和B来监听&服务器侦听端口A和B到响应

时间:2013-09-11 05:59:49

标签: c#

我需要创建一个客户端服务器应用程序,其中客户端使用端口1818发送请求,让服务器说“Hello”,服务器监听同一端口,然后服务器应该使用端口1819回复,让我们说“早上好”,客户端应该用1819端口收听回复并打印标签或其他东西收到的消息 ..希望这会解释

服务器: -

namespace TCPListener
{
    public partial class Server : Form
    {
        public Server()
        {
            InitializeComponent();
        }

        static string output = "";

        public void createListener()
        {
            // Create an instance of the TcpListener class.
            TcpListener tcpListener = null;
            //IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
            //string ip="192.168.0.205";
            //IPAddress ipAddress = IPAddress.Parse(ip);
            IPAddress ipAddress = IPAddress.Any;
            try
            {
                // Set the listener on the local IP address 
                // and specify the port.
                tcpListener = new TcpListener(ipAddress, 1818);
                tcpListener.Start();
                output = "Waiting for a connection...";
            }
            catch (Exception e)
            {
                output = "Error: " + e.ToString();
                MessageBox.Show(output);
            }
            while (true)
            {
                // Always use a Sleep call in a while(true) loop 
                // to avoid locking up your CPU.
                Thread.Sleep(10);
                // Create a TCP socket. 
                // If you ran this server on the desktop, you could use 
                // Socket socket = tcpListener.AcceptSocket() 
                // for greater flexibility.
                TcpClient tcpClient = tcpListener.AcceptTcpClient();
                // Read the data stream from the client. 
                byte[] bytes = new byte[256];
                NetworkStream stream = tcpClient.GetStream();
                stream.Read(bytes, 0, bytes.Length);
                SocketHelper helper = new SocketHelper();
                //helper.processMsg(tcpClient, stream, bytes);
                helper.processMsg("192.168.0.205", stream, bytes);
            }
        }

        class SocketHelper
        {
            TcpClient mscClient;
            string mstrMessage;
            string mstrResponse;
            byte[] bytesSent;

            public void processMsg(TcpClient client, NetworkStream stream, byte[] bytesReceived)
            {
                // Handle the message received and  
                // send a response back to the client.
                mstrMessage = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length);
                mscClient = client;
                //mstrMessage = mstrMessage.Substring(0, 5);
                //if (mstrMessage.Equals("Hello"))
                //{
                //    mstrResponse = "Goodbye";
                //}
                //else
                //{
                //    mstrResponse = "What?";
                //}
                if (mstrMessage.Length>0)
                {
                    mstrResponse = mstrMessage;
                }
                else
                {
                    mstrResponse = "You have sent blank message";
                }
                bytesSent = Encoding.ASCII.GetBytes(mstrResponse);
                stream.Write(bytesSent, 0, bytesSent.Length);
            }

            public void processMsg(string ip, NetworkStream stream, byte[] bytesReceived)
            {
                // Handle the message received and  
                // send a response back to the client.
                mscClient = new TcpClient(ip, 1819);
                mstrMessage = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length);                
                //mstrMessage = mstrMessage.Substring(0, 5);
                //if (mstrMessage.Equals("Hello"))
                //{
                //    mstrResponse = "Goodbye";
                //}
                //else
                //{
                //    mstrResponse = "What?";
                //}
                if (mstrMessage.Length > 0)
                {
                    mstrResponse = mstrMessage;
                }
                else
                {
                    mstrResponse = "You have sent blank message";
                }
                bytesSent = Encoding.ASCII.GetBytes(mstrResponse);
                stream.Write(bytesSent, 0, bytesSent.Length);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Text = "Now Listening";
            this.createListener();
        }
    }
}

客户: -

namespace TCPClient
{
    public partial class Client : Form
    {
        static string output = "";
        public Client()
        {
            InitializeComponent();
        }
        public void createListener()
        {
            // Create an instance of the TcpListener class.
            TcpListener tcpListener = null;            
            IPAddress ipAddress = IPAddress.Any;
            try
            {
                // Set the listener on the local IP address 
                // and specify the port.
                tcpListener = new TcpListener(ipAddress, 1819);
                tcpListener.Start();
                output = "Waiting for a connection...";
            }
            catch (Exception e)
            {
                output = "Error: " + e.ToString();
                MessageBox.Show(output);
            }
            while (true)
            {
                // Always use a Sleep call in a while(true) loop 
                // to avoid locking up your CPU.
                Thread.Sleep(10);
                // Create a TCP socket. 
                // If you ran this server on the desktop, you could use 
                // Socket socket = tcpListener.AcceptSocket() 
                // for greater flexibility.
                TcpClient tcpClient = tcpListener.AcceptTcpClient();
                // Read the data stream from the client. 
                byte[] bytes = new byte[256];
                NetworkStream stream = tcpClient.GetStream();                
                stream.Read(bytes, 0, bytes.Length);

            }
        }
        static string Connect(string serverIP, string message)
        {
            string output = "";

            try
            {
                // Create a TcpClient. 
                // The client requires a TcpServer that is connected 
                // to the same address specified by the server and port 
                // combination.
                Int32 port = 1818;
                TcpClient client = new TcpClient(serverIP, port);

                // Translate the passed message into ASCII and store it as a byte array.
                Byte[] data = new Byte[256];
                data = System.Text.Encoding.ASCII.GetBytes(message);

                // Get a client stream for reading and writing. 
                // Stream stream = client.GetStream();
                NetworkStream stream = client.GetStream();

                // Send the message to the connected TcpServer. 
                stream.Write(data, 0, data.Length);

                output = "Sent: " + message;
                MessageBox.Show(output);

                // Buffer to store the response bytes.
                data = new Byte[256];

                // String to store the response ASCII representation.
                String responseData = String.Empty;

                // Read the first batch of the TcpServer response bytes.
                Int32 bytes = stream.Read(data, 0, data.Length);
                responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                output = "Received: " + responseData;
                MessageBox.Show(output);
                // Close everything.
                stream.Close();
                client.Close();
                return responseData;
            }
            catch (ArgumentNullException e)
            {
                output = "ArgumentNullException: " + e;
                MessageBox.Show(output);
                return e.Message;
            }
            catch (SocketException e)
            {
                output = "SocketException: " + e.ToString();
                MessageBox.Show(output);
                return e.Message;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // In this code example, use a hard-coded 
            // IP address and message. 
            string serverIP = "192.168.0.205";
            string message = textBox1.Text;
            textBox2.Text=Connect(serverIP, message);
        }
    }
}

0 个答案:

没有答案