Port is closed even I opened it - c#

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());
}

Related

Save connected Socket in Dictionary

I'm trying to save a connected socket in a dictionary so my API doesn't have to create a new connection every time. My problem is that the socket gets disposed.
So when I call GetConnection() a second time socket.connected is false and socket.Available.Message is "Cannot access a disposed object. Object name: 'System.Net.Sockets.Socket'.".
public static class ModbusSocket
{
private static Dictionary<IPAddress, Socket> socketList;
public static Socket GetConnection(string server, int port)
{
if (socketList is null)
{
socketList = new Dictionary<IPAddress, Socket>();
}
IPAddress iPAddress = IPAddress.Parse(server);
if (socketList.ContainsKey(iPAddress))
{
var socket = socketList[iPAddress];
if (socket.Connected)
{
return socket;
}
else
{
socketList.Remove(iPAddress);
socket = new Socket(iPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint(iPAddress, port);
socket.Connect(ipe);
socketList.Add(iPAddress, socket);
return socket;
}
}
else
{
Socket socket = new Socket(iPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint(iPAddress, port);
socket.Connect(ipe);
socketList.Add(iPAddress, socket);
return socket;
}
}
}
OMG I found the issue...
I invoked it with using:
using (Socket s = ModbusSocket.GetConnection(hostIp, port))
{
var telegram = new Telegram();
telegram.Set(0, AddressConst.PositionWindow, 4);
var response = telegram.SendAndReceive(s);
var result = BitConverter.ToInt32(new byte[] { response.Byte19, response.Byte20, response.Byte21, response.Byte22 }, 0);
return result;
}

c# socket connection with multi threading telnet

**i use c# this code socket connection with multi threading **
i need set time out to my socket connection telnet
string ip = "";
int port = 23;
string str = "";
IPAddress address = IPAddress.Parse(ip);
IPEndPoint ipEndPoint = new IPEndPoint(address, port);
Socket socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Connect((EndPoint)ipEndPoint);
try
{
byte[] numArray = new byte[1024];
while (socket.Connected) {
int count = socket.Receive(numArray);
str += Encoding.ASCII.GetString(numArray, 0, count);
Console.WriteLine(str);
}
socket.Close();
}
catch (ArgumentNullException ex)
{
}
You can either create a timer to do this or what I like to do is give the socket.connected a timeframe and base my connection of that. You'd obviously need to modify the time per your conditions, but this example has worked for me in the past.
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect using a timeout (5 seconds)
IAsyncResult result = socket.BeginConnect( iP, iPort, null, null );
bool success = result.AsyncWaitHandle.WaitOne( 5000, true );
if ( socket.Connected )
{
socket.EndConnect( result );
}
else
{
//Be sure to close socket
socket.Close();
throw new ApplicationException("Failed to connect the server. Try again.");
}
I saw another example someone else did with timer, but I have not personally used this, so whichever you are more comfortable with. start a timer (timer_connection), if time is up, check whether socket connection is connected (if(m_clientSocket.Connected)), if not, pop up timeout error
private void connect(string ipAdd,string port)
{
try
{
SocketAsyncEventArgs e=new SocketAsyncEventArgs();
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(serverIp);
int iPortNo = System.Convert.ToInt16(serverPort);
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
//m_clientSocket.
e.RemoteEndPoint = ipEnd;
e.UserToken = m_clientSocket;
e.Completed+=new EventHandler<SocketAsyncEventArgs>(e_Completed);
m_clientSocket.ConnectAsync(e);
if (timer_connection != null)
{
timer_connection.Dispose();
}
else
{
timer_connection = new Timer();
}
timer_connection.Interval = 2000;
timer_connection.Tick+=new EventHandler(timer_connection_Tick);
timer_connection.Start();
}
catch (SocketException se)
{
lb_connectStatus.Text = "Connection Failed";
MessageBox.Show(se.Message);
}
}
private void e_Completed(object sender,SocketAsyncEventArgs e)
{
lb_connectStatus.Text = "Connection Established";
WaitForServerData();
}
private void timer_connection_Tick(object sender, EventArgs e)
{
if (!m_clientSocket.Connected)
{
MessageBox.Show("Connection Timeout");
//m_clientSocket = null;
timer_connection.Stop();
}
}

Client And Server Socket Connection using C#

I created two projects one with client and other with server to exchange text between both of them;on same computer i run those exe.
MY Client Side Connection Code connection looked :
using (SocketClient sa = new SocketClient(host, port))
{
sa.Connect();
Console.WriteLine(sa.SendReceive("Message #" + i.ToString()));
}
sa.Disconnect();
while socketclient is my class which contain these methods and constructor:
internal SocketClient(String hostName, Int32 port)
{
IPHostEntry host = Dns.GetHostEntry(hostName);
IPAddress[] addressList = host.AddressList;
this.hostEndPoint = new IPEndPoint(addressList[addressList.Length - 1], port);
this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
}
internal void Connect()
{
SocketAsyncEventArgs connectArgs = new SocketAsyncEventArgs();
connectArgs.UserToken = this.clientSocket;
connectArgs.RemoteEndPoint = this.hostEndPoint;
connectArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnect);
clientSocket.ConnectAsync(connectArgs);
autoConnectEvent.WaitOne();
SocketError errorCode = connectArgs.SocketError;
if (errorCode != SocketError.Success)
{
throw new SocketException((Int32)errorCode);
}
}
internal void Disconnect()
{
clientSocket.Disconnect(false);
}
private void OnConnect(object sender, SocketAsyncEventArgs e)
{
autoConnectEvent.Set();
this.connected = (e.SocketError == SocketError.Success);
}
internal String SendReceive(String message)
{
if (this.connected)
{
Byte[] sendBuffer = Encoding.ASCII.GetBytes(message);
SocketAsyncEventArgs completeArgs = new SocketAsyncEventArgs();
completeArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length);
completeArgs.UserToken = this.clientSocket;
completeArgs.RemoteEndPoint = this.hostEndPoint;
completeArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);
clientSocket.SendAsync(completeArgs);
AutoResetEvent.WaitAll(autoSendReceiveEvents);
return Encoding.ASCII.GetString(completeArgs.Buffer, completeArgs.Offset,completeArgs.BytesTransferred);
}
else
{
throw new SocketException((Int32)SocketError.NotConnected);
}
}
while on server side code looks like that:
SocketListener sl = new SocketListener(numConnections, bufferSize);
sl.Start(port);
Console.WriteLine("Server listening on port {0}.
Press any key to terminate the server process...", port);
Console.Read();
sl.Stop();
Socket listener is my class which contain this method and constructor :
internal SocketListener(Int32 numConnections, Int32 bufferSize)
{
this.numConnectedSockets = 0;
this.numConnections = numConnections;
this.bufferSize = bufferSize;
this.readWritePool = new SocketAsyncEventArgsPool(numConnections);
this.semaphoreAcceptedClients = new Semaphore(numConnections, numConnections);
for (Int32 i = 0; i < this.numConnections; i++)
{
SocketAsyncEventArgs readWriteEventArg = new SocketAsyncEventArgs();
readWriteEventArg.Completed += new EventHandler<SocketAsyncEventArgs> (OnIOCompleted);
readWriteEventArg.SetBuffer(new Byte[this.bufferSize], 0, this.bufferSize);
this.readWritePool.Push(readWriteEventArg);
}
}
internal void Start(Int32 port)
{
IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;
IPEndPoint localEndPoint = new IPEndPoint(addressList[addressList.Length - 1], port);
this.listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
this.listenSocket.ReceiveBufferSize = this.bufferSize;
this.listenSocket.SendBufferSize = this.bufferSize;
if (localEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
{
this.listenSocket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, false);
this.listenSocket.Bind(new IPEndPoint(IPAddress.IPv6Any, localEndPoint.Port));
}
else
{
this.listenSocket.Bind(localEndPoint);
}
this.listenSocket.Listen(this.numConnections);
this.StartAccept(null);
mutex.WaitOne();
}
I have already port forward of my router because of server side exe which didn't listen without port forwarding.
it is working fine with send and receive on same pc and same port at home.
While when i try to run both of codes exe on my office computer it throws exception at following line:
Exception thrown by socket
Could any one guide me whats the problem and how to resolve it ?
Thanks
Have you tried temporary disable your Windows firewall ?

Socket application

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();
}
}
}

C# Creating chat rooms with multi client-server Sockets

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?

Categories