Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a string over a socket in C#

Tags:

string

c#

sockets

I am testing this locally, so the IP to connect to can be localhost or 127.0.0.1

After sending it, it receives a string back. That would also be handy.

like image 990
Lolmewn Avatar asked Jan 07 '12 22:01

Lolmewn


2 Answers

Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(server);
System.Net.IPEndPoint remoteEP = new IPEndPoint(ipAdd, 3456);
soc.Connect(remoteEP);

For connecting to it. To send something:

//Start sending stuf..
byte[] byData = System.Text.Encoding.ASCII.GetBytes("un:" + username + ";pw:" + password);
soc.Send(byData);

And for reading back..

byte[] buffer = new byte[1024];
int iRx = soc.Receive(buffer);
char[] chars = new char[iRx];

System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
System.String recv = new System.String(chars);
like image 76
Lolmewn Avatar answered Oct 06 '22 03:10

Lolmewn


Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAdd = System.Net.IPAddress.Parse(m_ip);
IPEndPoint remoteEP = new IPEndPoint(ipAdd, m_port);

socket.Connect(remoteEP);

byte[] byData = System.Text.Encoding.ASCII.GetBytes("Message");
socket.Send(byData);


socket.Disconnect(false);
socket.Close();
like image 41
Masoud Siahkali Avatar answered Oct 06 '22 03:10

Masoud Siahkali