c#套接字编程客户端/服务器 [英] c# socket programming client/server

查看:54
本文介绍了c#套接字编程客户端/服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好......

我的问题是:



-Client:

1-send the 3个数字的总和:第一,第二,期末考试

2 - 接收并显示来自用户的信件



-Server:

1 - 来自客户的接收号码

2-compare:

N< 50→→→D

50> = N< 60→→→C

60< = N< 70→→→B

70< = N< 80→→→ B +

80< = N< 90→→→A

90< = N< 100→→→A +

3 - 发信给客户





这是我的c#代码:

hello...
My question is:

-Client:
1-send the Sum of 3 numbers:First,Second,Final Exam
2-Receive and Show a Letter From the user

-Server:
1-Receive number from the client
2-compare:
N<50→→→"D"
50>=N<60→→→"C"
60<=N<70→→→"B"
70<=N<80→→→"B+"
80<=N<90→→→"A"
90<=N<100→→→"A+"
3-Send the Letter to Client


Here is my c# Code:

//server socket Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Data.OleDb;

namespace Server
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("The Server is Run And Wait .....");

            // Create Server Socket to recive
            TcpListener Ls = new TcpListener(7110);
            Ls.Start();

            //blocks until a client has connected to the server
            while (true)  // to make the server always on
            {
                // to connect with clients
                TcpClient client = Ls.AcceptTcpClient();
                NetworkStream clientStream = client.GetStream();
                byte[] message = new byte[4096];
                clientStream.Read(message, 0, message.Length);


                /////////////////////////////////////////////////

                string src = Encoding.ASCII.GetString(message, 0, message.Length);
                 
                
                
                OleDbConnection cnn = new OleDbConnection();
                cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\\c++\\database.accdb";
                cnn.Open();

                OleDbDataAdapter adb = new OleDbDataAdapter("Select sip From Table1 Where Site='"+src.Trim('\0')+"'",cnn);
                System.Data.DataSet dat = new System.Data.DataSet();
                adb.Fill(dat);
                string Msgout = dat.Tables[0].Rows[0].ItemArray[0].ToString();

                //////////////////////////////////////////////////

                NetworkStream ServerStream = client.GetStream();
                byte[] buffer = Encoding.ASCII.GetBytes(Msgout);
                ServerStream.Write(buffer, 0, buffer.Length);

                ServerStream.Flush();
                client.Close();
 
            }
            Ls.Stop();

            

        }
    }
}

//Client Socket 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.IO;

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

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            
            
              
        }

        private void button1_Click(object sender, EventArgs e)
        {

            // creat client Socket  to send
            TcpClient Sending = new TcpClient("localhost",7110);
            byte[] data =Encoding.ASCII.GetBytes(textBox1.Text);
            NetworkStream datastream = Sending.GetStream();
            datastream.Write(data, 0, data.Length);


            data = new byte[256];
            datastream.Read(data,0,data.Length);
            string ResponseData;
            ResponseData = Encoding.ASCII.GetString(data, 0, data.Length);



            textBox2.Text = textBox2.Text + Environment.NewLine + ResponseData;
            textBox1.Text = "";
            Sending.Close();


           
        

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //this.Close();
            Application.Exit();
        }
    }
}

已添加代码块[/ Edit]

Code block added[/Edit]

推荐答案

和你的问题是????



但是从我的代码中我发现了3个主要问题。

1 - 你永远不会发送或获得大小的消息。 TCP / IP不是面向消息的协议,因此您可以发送10个字节,但另一侧可能在第一次读取时接收3个字节。因此,您应该发送大小,然后是内容,另一方必须读取大小,分配具有正确大小的缓冲区,然后继续阅读,直到确保收到所有消息为止。



2 - 如果您纠正此类错误,则在本地独立,此消息将始终正确到达。但是你使用GetString传递完整的消息长度(这是你的4096字节的缓冲区)。你应该传递真正的消息大小(或者在最坏的情况下,clientStream.Read方法返回的字节数)。



3 - 你的监听器将处理一次一个客户。正确的方法是在收到连接时创建一个新线程,这样许多客户端可以并行连接。
And your question is????

But from your code I spot 3 main problems.
1 - You never send or get the size of the message. TCP/IP is not a "message oriented" protocol, so you may send 10 bytes, but the other side may receive 3 bytes on the first read. So, you should be sending the size, then the content, and the other side must read the size, allocate the buffer with the right size, and then continue reading until it is guaranteed that all the message was received.

2 - Independent if you correct such error or not, locally the message will always arrive correctly. But then you are using GetString passing the full message length (which is your buffer with 4096 bytes). You should be passing the real message size (or on the worst case, the number of bytes returned by the clientStream.Read method).

3 - Your listener will process one client at a time. The correct will be to create a new thread when a connection is received, this way many clients can connect in parallel.


我们还需要知道TCP / IP套接字是基于流的。服务器端的三个发送操作并不意味着客户端有三个读操作。相反,客户端可能会在一次或两次读取操作中获取所有数据。
We also need to know that TCP/IP sockets are stream based. Three send operations on the server side don't mean three read operations on the client side. Instead the client might get all the data in one or two read operations.


这篇关于c#套接字编程客户端/服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆