通过TCP传递JSON数据,套接字编程c#

时间:2017-09-09 08:33:15

标签: c# json sockets server tcpclient

我创建了一个桌面软件服务器系统,它从客户端接受字符串并插入数据库,这里是服务器代码

public class TcpServer
{
    public TcpListener _server;
    public Boolean _isRunning;
    Data_connection dbobject = new Data_connection();
    SQLiteConnection SQLconnect = new SQLiteConnection();
    Window win;
    public DataTable dt_stored;
    public List<string> connected_users;

    public TcpServer(int port,Window _win)
    {
        win = _win;
        _server = new TcpListener(IPAddress.Any, port);
        connected_users = new List<string>();
        _server.Start();

        _isRunning = true;

        SQLconnect.ConnectionString = dbobject.datalocation();

        Thread th = new Thread(listenClients);
        th.Start();
        //listenClients();
    }
    public void listenClients()
    {
        while (_isRunning)
        {
            try
            {
                // wait for client connection
                TcpClient newClient = _server.AcceptTcpClient();

                // client found.
                // create a thread to handle communication
                Thread t = new Thread(new ParameterizedThreadStart(HandleClient));

                t.Start(newClient);
            }catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

    public void HandleClient(object obj)
    {
        // retrieve client from parameter passed to thread
        TcpClient client = (TcpClient)obj;

        StreamWriter sWriter = new StreamWriter(client.GetStream(), Encoding.ASCII);
        StreamReader sReader = new StreamReader(client.GetStream(), Encoding.ASCII);


        // reads from client stream
        string sData = sReader.ReadLine();

        if (!string.IsNullOrEmpty(sData))
        {
            //store to sqlite database
            insertToDB(sData, 0);
            string[] arr = sData.Split(',');
            //add name to list
            connected_users.Add(arr[0]);
            //select all students from the DB
            SelectAllStudents();
            ////show
            //MessageBox.Show(sData);

            // to write data  back.
            string allnames = convertDtNamesToString();
            sWriter.WriteLine(allnames);
            sWriter.Flush();
        }
    }

    private string convertDtNamesToString()
    {
        string data = "";
        foreach(DataRow row in dt_stored.Rows)
        {
            data = data +row[1].ToString()+",";
        }
        return data;
    }

    public void SelectAllStudents()
    {
        if (SQLconnect.State != ConnectionState.Open)
        {
            SQLconnect.Open();
        }
        SQLiteCommand cmd = new SQLiteCommand("select * from Students", SQLconnect);
        SQLiteDataAdapter da = new SQLiteDataAdapter();
        dt_stored = new DataTable();
        da.SelectCommand = cmd;
        da.Fill(dt_stored);

        if (SQLconnect.State != ConnectionState.Closed)
        {
            SQLconnect.Close();
        }
    }

    private void insertToDB(string sData,int n)
    {
        if(n>20)
        {
            MessageBox.Show("Error inserting data");
            return; ;
        }
        if (SQLconnect.State != ConnectionState.Open)
        {
            SQLconnect.Open();
        }
        //create students table if not exist
        try
        {
            SQLiteCommand SQLcommand = new SQLiteCommand();
            SQLcommand = SQLconnect.CreateCommand();
            SQLcommand.CommandText = "CREATE TABLE IF NOT EXISTS Students" + "( Name TEXT, Phone TEXT, Address Text, Passport Text);";
            SQLcommand.ExecuteNonQuery();
            SQLcommand.Dispose();
            // MessageBox.Show("Table Created");

            //insert student
            string[] data = sData.Split(',');
            SQLiteCommand cmd = new SQLiteCommand();

            cmd = SQLconnect.CreateCommand();
            cmd.CommandText = "insert into Students values (@_name,@_phone,@_address,@_passport)";
            cmd.Parameters.AddWithValue("@_name", data[1]);
            cmd.Parameters.AddWithValue("@_phone", data[2]);
            cmd.Parameters.AddWithValue("@_address", data[3]);
            cmd.Parameters.AddWithValue("@_passport", data[4]);

            cmd.ExecuteNonQuery();
            cmd.Dispose();
        }
        catch (Exception ex)
        {
            n++;
            Thread.Sleep(200);
            insertToDB(sData,n);
        }
        finally
        {
            if (SQLconnect.State != ConnectionState.Closed)
            {
                SQLconnect.Close();
            }
        }
        //MessageBox.Show("Data Inserted");
    }
}

我有一个客户端sofwtare,它也将数据发送到服务器以插入数据库,这里的代码也是

class Client
{
    private TcpClient _tcpclient;

    private StreamReader _sReader;
    private StreamWriter _sWriter;
    public static List<string> lst_storeddata = new List<string>();

    private Boolean _isConnected;
    string name;
    string phone;
    string address;
    string passport;
    public Client(string _name, string _phone, string _address, string _passport)
    {
        //server ip
        String ipAddress = "127.0.0.1";
        //String ipAddress = "192.168.43.15";
        //port number
        int portNum = 8585;
        try
        {
            _tcpclient = new TcpClient();
            _tcpclient.Connect(ipAddress, portNum);

            name = _name;
            phone = _phone;
            address = _address;
            passport = _passport;

            HandleCommunication();
        }catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    public void HandleCommunication()
    {
        _sReader = new StreamReader(_tcpclient.GetStream(), Encoding.ASCII);
        _sWriter = new StreamWriter(_tcpclient.GetStream(), Encoding.ASCII);

        string clientData = Environment.MachineName+","+name + "," + phone + "," + address + "," + passport;
        _sWriter.WriteLine(clientData);
        _sWriter.Flush();

        // receive data
        String sDataIncomming = _sReader.ReadLine();
        lst_storeddata = (sDataIncomming.Split(',')).ToList();      
        _sWriter.Close();
        _tcpclient.Close();
    }
}

我现在的挑战是,我不知道如何去做,通过网络发送JSON数据,而不是字符串数组。

请帮忙。

1 个答案:

答案 0 :(得分:0)

Json序列化将对象转换为对象的字符串表示形式。如果您现有的代码工作正常,那么您可以将任何POCO序列化为字符串并重复使用。

C#事实上的标准json序列化库是Json.NET,通常通过Newtonsoft.json nuget包引用。