gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:08:58 30 4
gpt4 key购买 nike

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

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");
}
}

我有一个客户端软件,它也将数据发送到服务器以插入数据库,这也是代码
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 数据。

请帮忙。

最佳答案

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

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

关于c# - 通过 TCP 传递 JSON 数据,套接字编程 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46128734/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com