por - sockets e hilos en c#
Pasar datos JSON por TCP, programaciĆ³n de socket c# (1)
He creado un sistema de servidor de software de escritorio, que acepta cadenas de clientes e inserta en bases de datos, aquí está el código del servidor
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");
}
}
Y tengo un cliente sofwtare, que también envía datos al servidor para insertar en databse, y aquí está el código también
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();
}
}
Mi desafío ahora es: no sé cómo hacerlo, enviando datos JSON a través de la red, en lugar de una matriz de cadenas.
Por favor ayuda.
La serialización Json convierte un objeto en una representación de cadena del objeto. Si su código actual funciona bien, entonces puede serializar cualquier POCO en una cadena y reutilizarlo.
La biblioteca de serialización json estándar de facto para C # es Json.NET generalmente referenciada a través del paquete Nuget Newtonsoft.json.