my software consists of two parts. one of them is client, i can connect my device on router via ethernet and i can send a command ( data ) then i am starting to wait getting response from my device, but i cannot figure out how i could get responce, despite of the fact that i have been looking for similar socket application. i have studying c# for 2 weeks. Would you help me about this topic ?
If you can help me, i will be really pleasure you.
namespace sencron_socket
{
class Program
{
static Socket sck;
static Socket scks;
static byte[] Buffer { get; set; }
static void Main(string[] args)
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localendpoint = new IPEndPoint(IPAddress.Parse("172.16.204.101"), 50007); //50007 bidirectional interface The event
try
{
sck.Connect(localendpoint);
if (sck.Poll(-1, SelectMode.SelectWrite))
{
Console.WriteLine("this socket is writable");
}
else if (sck.Poll(-1, SelectMode.SelectError))
{
Console.WriteLine("this socket has an error");
}
}
catch
{
Console.Write(" unable ");
Main(args);
}
Console.Write("enter text: ");
string text = Console.ReadLine();
byte[] data = Encoding.ASCII.GetBytes(text);
sck.Send(data);
Console.Write(" data sent! \r\n ");
//Console.Write(" press ant key to continue ");
// Console.Read();
sck.Close();
scks = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
scks.Bind(new IPEndPoint(IPAddress.Parse("172.16.204.104"),0));
scks.Listen(1);
Console.Write(" it is ok until this step ");
// ???????????????????????????????????????????????????????
// i think that my problem starts next line with Accept()
Socket accepted = scks.Accept();
Console.Write(" BURDA 222 \r\n");
IPEndPoint remoteEndPoint = (IPEndPoint)accepted.RemoteEndPoint;
Buffer = new byte[accepted.SendBufferSize];
int bytesRead = accepted.Receive(Buffer);
byte[] formatted = new byte[bytesRead];
/* for (int i = 0; i < bytesRead; i++)
{
formatted[i] = Buffer[i];
}*/
Console.Write(" BURDA 3333 ");
string strData = Encoding.ASCII.GetString(formatted);
Console.Write(strData + "\r\n");
scks.Close();
accepted.Close();
Console.Read();
}
}
}
Related
I need help with solving my problem.
I use Comtrend VR 302e.
I have setted up port forwarding like this.
But when I open the online port checker or telnet, it tells me that my port is closed. Why?
Here is the setup
Codes:
Server
static byte[] data; // 1
static Socket socket; // 1
static void Main(string[] args)
{
while (true)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(IPAddress.Any, 3459));
socket.Listen(10);
Socket acceptData = socket.Accept();
data = new byte[acceptData.SendBufferSize];
int j = acceptData.Receive(data);
byte[] adata = new byte[j];
for (int i = 0; i < j; i++)
{
adata[i] = data[i];
}
string dat = Encoding.Default.GetString(adata);
Console.WriteLine(dat);
}
}
Client here
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try // 1
{
s.Connect(IPAddress.Parse(textBox1.Text), 3459); // 2
string q = "It works"; // 3
byte[] data = Encoding.Default.GetBytes(q); // 3
s.Send(data);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Good afternoon, i've been trying to make a system kinda like skype in terms of convo groups, being able to enter a group and chatting with others that were online only within that group, issue is i dont know how i could separate this chat room into several ones and making them independent from each other with just one server
Overall, im trying to have multi chat rooms with one server while being able to save one's conversation chat log and be able to read it back
The current code i have works only as 1 general chat room
Server Side:
static void Main(string[] args)
{
Socket newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Ip);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 6000);
newSocket.Bind(endPoint);
newSocket.Listen(10);
Console.Write("Waiting...\n");
while (true)
{
Socket auxSocket = newSocket.Accept();
ThreadLab a = new ThreadLab(auxSocket);
Thread novaThread = new Thread(new ThreadStart(a.Connect));
novaThread.Start();
}
}
The ThreadLab Class:
private Socket socket;
static int nmrUsers = 0;
static int indice;
static Socket[] listaSockets = new Socket[10];
static ArrayList listaUtilizadores = new ArrayList();
public ThreadLab(Socket s)
{
socket = s;
listaSockets[indice++] = s;
}
public void Connect()
{
IPEndPoint aux = (IPEndPoint)socket.RemoteEndPoint;
Console.Write("Client " + aux.Address.ToString() + " connected\n");
}
And the client side that will have the reader and writer:
private static Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Ip);
private static ThreadStart tSReader;
private static ThreadStart tSWriter;
private static Thread tReader;
private static Thread tWriter;
private static string nome;
static void Main(string[] args)
{
IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6000);
tSReader = new ThreadStart(reader);
tSWriter = new ThreadStart(writer);
tReader = new Thread(tSReader);
tWriter = new Thread(tSWriter);
try
{
client.Connect(clientEndPoint);
}
catch (SocketException e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
tReader.Start();
tWriter.Start();
}
public static void writer()
{
string str;
byte[] data = new byte[1024];
nome = Console.ReadLine();
data = Encoding.ASCII.GetBytes(nome);
client.Send(data, data.Length, SocketFlags.None);
do
{
str = Console.ReadLine();
data = Encoding.ASCII.GetBytes(str);
client.Send(data, data.Length, SocketFlags.None);
} while (str != "exit");
client.Shutdown(SocketShutdown.Both);
tReader.Abort();
client.Close();
}
public static void reader()
{
byte[] data = new byte[1024];
int recv;
while (true)
{
try
{
recv = client.Receive(data);
}
catch (Exception e)
{
Console.WriteLine("Erro: " + e.Message);
Console.ReadLine();
break;
}
Console.WriteLine("\n" + Encoding.ASCII.GetString(data, 0, recv));
}
}
}
Someone can help me?
I am working on multi thread server and clients written in C#.So Guide
me how can I make multi thread in server for multi client.
This is my Server Code
class Program
{
static byte[] Buffer
{
get;
set;
}
static void Main(string[] args)
{
Program obj = new Program();
Console.WriteLine("Server");
obj.server_reciver();
}
static Socket sck;
public void server_reciver()
{
try
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint;
localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.2"), 1);
sck.Bind(localEndPoint);
sck.Listen(100);
while (true)
{
Socket accepted = sck.Accept();
// Buffer = new byte[accepted.ReceiveBufferSize];
Buffer = new byte[accepted.SendBufferSize];
int bytesRead = accepted.Receive(Buffer);
byte[] formatted = new byte[bytesRead];
//for (int i = 0; i < bytesRead; i++)
for (int i = 0; i < bytesRead; i++)
{
formatted[i] = Buffer[i];
//Console.WriteLine(Buffer[i] + "\r\n");
}
//string strData = Encoding.ASCII.GetString(Buffer);
string strData = Encoding.ASCII.GetString(formatted);
Console.Write("From Client=>" + strData + "\n");
Console.WriteLine("Enter the text:");
string data = Console.ReadLine();
byte[] reply = Encoding.ASCII.GetBytes(data);
accepted.Send(reply);
//accepted.Close();
accepted.Close();
}
sck.Close();
Console.Read();
}
catch (Exception ex)
{
}
}
}
This is my Client side and I make more then one client here is one
class Program
{
static byte[] Buffer
{
get;
set;
}
static Socket sck;
static void Main(string[] args)
{
Program obj = new Program();
obj.client_send();
}
public void client_send()
{
while (true)
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint;
localEndPoint = new IPEndPoint(IPAddress.Parse("182.188.247.244"), 1);
//localEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.45"), 1);
try
{
sck.Connect(localEndPoint);
}
catch
{
Console.Write("Unable to connect to remote end point!\r\n");
//Main(args);
}
try
{
Console.Write("Enter Text: ");
string text = Console.ReadLine();
byte[] data = Encoding.ASCII.GetBytes(text);
sck.Send(data);
Buffer = new byte[sck.SendBufferSize];
int bytesRead = sck.Receive(Buffer);
byte[] formatted = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
{
formatted[i] = Buffer[i];
//Console.WriteLine(Buffer[i] + "\r\n");
}
string strData = Encoding.ASCII.GetString(formatted);
Console.Write("From Server=>" + strData + "\n");
sck.Close();
}
catch(Exception )
{
}
}
Console.ReadLine();
}
}
Typically, you would keep Socket accepted = sck.Accept(); on the main thread, but once a request is received you would pass it to another thread for servicing. This allows the main thread to listed to another incoming request. You can use ThreadPool.QueueUserWorkItem to move the work to a background thread. Note that making it multi-threaded is going to give you problems since the response is read from Console. How is each worker thread to know that it gets the right data? But I assume you'll replace that with real server logic.
At some point, you may find that this doesn't scale. You're using blocking IO calls (Send and Receive) so your threads will spend a lot of time waiting. Non-blocking IO would be ideal, but it is more complicated to write.
I just started socket programming in c#. I wanted to develop a simple client-server echo application. The problem I encountered is when i try to echo the message back to the client, it does not receive it. I spent a lot of time searching for solution on variety of forums but i couldn't find any that would help me with my problem.
Thanks in advance.
Andrew
Here is the code:
Server:
static void Main(string[] args)
{
string data = "";
UdpClient server = new UdpClient(8008);
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine(" S E R V E R IS S T A R T E D ");
Console.WriteLine("* Waiting for Client...");
while (data != "q")
{
byte[] receivedBytes = server.Receive(ref remoteIPEndPoint);
data = Encoding.ASCII.GetString(receivedBytes);
Console.WriteLine("Handling client at " + remoteIPEndPoint + " - ");
Console.WriteLine("Message Received " + data.TrimEnd());
server.Send(receivedBytes, receivedBytes.Length,remoteIPEndPoint);
Console.WriteLine("Message Echoed to" + remoteIPEndPoint + data);
}
Console.WriteLine("Press Enter Program Finished");
Console.ReadLine(); //delay end of program
server.Close(); //close the connection
}
}
Client:
static void Main(string[] args)
{
string data = "";
byte[] sendBytes = new Byte[1024];
byte[] rcvPacket = new Byte[1024];
UdpClient client = new UdpClient();
IPAddress address = IPAddress.Parse(IPAddress.Broadcast.ToString());
client.Connect(address, 8008);
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine("Client is Started");
Console.WriteLine("Type your message");
while (data != "q")
{
data = Console.ReadLine();
sendBytes = Encoding.ASCII.GetBytes(DateTime.Now.ToString() + " " + data);
client.Send(sendBytes, sendBytes.GetLength(0));
rcvPacket = client.Receive(ref remoteIPEndPoint);
string rcvData = Encoding.ASCII.GetString(rcvPacket);
Console.WriteLine("Handling client at " + remoteIPEndPoint + " - ");
Console.WriteLine("Message Received: " + rcvPacket.ToString());
}
Console.WriteLine("Close Port Command Sent"); //user feedback
Console.ReadLine();
client.Close(); //close connection
}
I was able to get this working by making the client talk directly to the server instead of broadcasting:
var serverAddress = "127.0.0.1"; // Server is on the local machine
IPAddress address = IPAddress.Parse(serverAddress);
...unless I'm missing an important reason why you were using broadcast in your original code?
This is a program to search for strings from a file. The string required by the client is given from the client side, in my case, using telnet. The program I have written is a server side one. It accepts multiple clients.
But, the problems I am unable rectify are-
It doesn't check for strings from the file.
As soon as the client gets connected, the client cannot type in the strings they want to search in that particular file.
It doesn't send the reply back (i.e. If the string is present in the file or not) to the client. Its only shown on the server side.
How do I proceed further? Could someone tell me where am I going wrong? Could someone please help me out with the code?
This is my try at the program..
class Program
{
static void Main(string[] args)
{
IPAddress ipad = IPAddress.Parse("192.168.0.181");
TcpListener serversocket = new TcpListener(ipad, 8888);
TcpClient clientsocket = default(TcpClient);
Byte[] bytes = new Byte[256];
serversocket.Start();
Console.WriteLine(">> Server Started");
while(true)
{
clientsocket = serversocket.AcceptTcpClient();
Console.WriteLine("Accepted Connection From Client");
LineMatcher lm = new LineMatcher(clientsocket);
Thread thread = new Thread(new ThreadStart(lm.Run));
thread.Start();
Console.WriteLine("Client connected");
}
Console.WriteLine(" >> exit");
Console.ReadLine();
clientsocket.Close();
serversocket.Stop();
}
}
public class LineMatcher //I've jumbled it up here. Don't know what exactly to do..
{
public string fileName = "c:/myfile2.txt";
private TcpClient _client;
public LineMatcher(TcpClient client)
{
_client = client;
}
public void Run()
{
try
{
StreamReader sr = new StreamReader("c:/myfile2.txt");
using (var reader = new StreamReader(_client.GetStream()))
{
string line ="";
int lineNumber = 0;
while (null != (line = sr.ReadLine()))
{
lineNumber += 1;
byte[] data = new byte[1024];
NetworkStream stream = _client.GetStream();
//if (line.Equals(line))
for (int ct = stream.Read(data,0, data.Length-1); 0 < ct; ct = stream.Read(data,0,data.Length-1))
line += Encoding.ASCII.GetString(data, 0, ct);
line = line.Trim();
{
lineNumber.ToString();
data = Encoding.ASCII.GetBytes(line);
_client.Client.Send(data, data.Length, SocketFlags.None);
Console.WriteLine("Line {0} matches {1}", lineNumber, line);
}
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
Console.WriteLine("Closing client");
_client.Close();
}
}
I think you got some pieces in your Run-method swapped - here is a version that should do the job:
public void Run()
{
byte[] data;
try
{
using (var r = new StreamReader("c:/myfile2.txt"))
{
string line ="";
int lineNumber = 0;
while (null != (line = r.ReadLine()))
{
data = Encoding.ASCII.GetBytes(line + "\n");
_client.Client.Send(data, data.Length, SocketFlags.None);
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
Console.WriteLine("Closing client");
_client.Close();
}
Please note that I'm not 100% sure what you are trying to do (I think you want your textfile send line-by-line to your Terminal) - so you might have to change some bits here and there.
Don't know where the Stream-messes in your code came from but I guess you tried various tutorials/snippets and forgot to clean up ;)