I have a small problem in working with the client server.

The essence of the task is that I need the client to enter the line number and the text to be recorded in a text file, and this file should be stored on the server. The client and the server work fine for me, and I know how to write the text in the right line.

I can not understand just how I can connect the client and server while writing to the file, because, when transferring from client to server, I can’t normally convert message types to byte.

Tell me how to connect the client and the server for such a task.

Customer

class Program { static Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); static void Main(string[] args) { socket.Connect("127.0.0.1",904); Console.WriteLine("Vvedite nomerk stroki"); int number_line =Convert.ToInt32( Console.ReadLine()); Console.WriteLine("Vvedite text"); string line_text = Console.ReadLine(); byte[] buffer1 = Encoding.ASCII.GetBytes(number_line); byte[] buffer = Encoding.ASCII.GetBytes(line); socket.Send(buffer); socket.Send(buffer1); Console.ReadKey(); } } 

Server

 class Program { static Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); static void Main(string[] args) { socket.Bind(new IPEndPoint(IPAddress.Any, 904)); socket.Listen(5); Socket client = socket.Accept(); Console.WriteLine("Подключение к серверу"); byte[] buffer = new byte[1024]; byte[] buffer1 = new byte[1024]; client.Receive(buffer1); client.Receive(buffer); Console.WriteLine(Encoding.ASCII.GetString(buffer)); Console.WriteLine(Encoding.ASCII.GetString(buffer1)); Console.ReadKey(); } } 

Writing to a text file by line number

 var text = File.ReadAllLines("1.txt").ToList(); text.Insert(number_line,line_text); File.WriteAllLines("1.txt", text.ToArray()); 
  • If you correctly grasp the essence of the question, then look here : the packet structure (so that you can send an arbitrary number of bytes, and not 1024) and make by analogy for your transport. And it's a pity that you have the insertion of lines : it would be possible to do less back and forth conversions, without chasing bytes into lines and back, to confine to File.ReadAllBytes / File.WriteAllBytes - AK
  • In general, I need to do the job. The essence of the task is that I need the client to enter the line number and the text to be recorded in a text file, and this file should be stored on the server. I know how to make all the parts separately, but I don’t know how to combine them together. That is the whole question. - Alexander

0