'Passing JSON Data over TCP, Socket programming c#
I have created a desktop software server system, which accepts string from client and insert into database, here is the server code
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");
}
}
And i have a client sofwtare, which also send data to the server to insert into databse, and here is the code also
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();
}
}
My challenge now is, i don't know how to go about it, sending JSON data through network, instead of string array.
Please help.
Solution 1:[1]
Json serialization turns an object into a string representation of the object. If your existing code works ok then you can serialize any POCO into a string and reuse it.
The de facto standard json serialization library for C# is Json.NET usually referenced via the Newtonsoft.json nuget package.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Johannes Overmann |