I had fix my Problem Cannot access a disposed object. in c# client & Server
Following Points I Used.
Used Using for Scope Limitation
i am not Closed Socket Object
class Client
{
static void Main(string[] args)
{
Console.Title = "Client Chat";
byte[] bytes = new byte[1024];// data buffer for incoming data
string data = null;
// connect to a Remote device
try
{
// Establish the remote end point for the socket
IPHostEntry ipHost = Dns.Resolve("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 95);
using (Socket Socketsender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Socketsender.Connect(ipEndPoint);
Console.WriteLine("\n\n\tSocket Connecting To Java Server...." + Socketsender.RemoteEndPoint.ToString());
while (true)
{
Console.Write("\n\n\tClient::");
string theMessage = Console.ReadLine();
byte[] msg = Encoding.ASCII.GetBytes(theMessage);
// Send the data through the socket
int bytesSent = Socketsender.Send(msg);
//Recieved from Java Server Message
int bytesRec = Socketsender.Receive(bytes);
Console.WriteLine("\n\n\tJava Server Says:: {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
}
//Socketsender.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
You create your Socket handler object outside the loop and close it inside the loop. The second pass through your loop you are looking at a Socket object that you have already closed.
Don't close your Socket until you are finished with it.
Related
So I have the code listed below for server client communication It works fine as long as you start both programms on the same PC but if I try to connect two seperate Pcs it doesn't work does anyone know where I have to put in the ip? I added some Console.Writelines to getter with there outputs as a comment
// ExecuteClient() Method
static void ExecuteClient(string message)
{
try
{
// Establish the remote endpoint
// for the socket. This example
// uses port 11111 on the local
// computer.
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
Console.WriteLine(ipHost); //System.Net.IPHostEntry
IPAddress ipAddr = ipHost.AddressList[0];
Console.WriteLine(ipHost.AddressList.ToString()); //System.Net.IPAddress[]
Console.WriteLine(ipAddr); //gives back an ip v6 address
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
Console.WriteLine(localEndPoint);
// Creation TCP/IP Socket using
// Socket Class Costructor
Console.WriteLine("AddressFamily: " + ipAddr.AddressFamily.ToString()); //InterNetworkV6
Socket sender = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
// Connect Socket to the remote
// endpoint using method Connect()
sender.Connect(localEndPoint);
// We print EndPoint information
// that we are connected
Console.WriteLine("Socket connected to -> {0} ",
sender.RemoteEndPoint.ToString());
// Creation of messagge that
// we will send to Server
byte[] messageSent = Encoding.ASCII.GetBytes("<EOF> " + message);
int byteSent = sender.Send(messageSent);
// Data buffer
byte[] messageReceived = new byte[1024];
// We receive the messagge using
// the method Receive(). This
// method returns number of bytes
// received, that we'll use to
// convert them to string
int byteRecv = sender.Receive(messageReceived);
Console.WriteLine("Message from Server -> {0}",
Encoding.ASCII.GetString(messageReceived,
0, byteRecv));
// Close Socket using
// the method Close()
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
// Manage of Socket's Exceptions
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//ExecuteServer method
public static void ExecuteServer()
{
// Establish the local endpoint
// for the socket. Dns.GetHostName
// returns the name of the host
// running the application.
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
// Creation TCP/IP Socket using
// Socket Class Costructor
Socket listener = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
// Using Bind() method we associate a
// network address to the Server Socket
// All client that will connect to this
// Server Socket must know this network
// Address
listener.Bind(localEndPoint);
// Using Listen() method we create
// the Client list that will want
// to connect to Server
listener.Listen(10);
while (true)
{
//Console.WriteLine("Waiting connection ... ");
// Suspend while waiting for
// incoming connection Using
// Accept() method the server
// will accept connection of client
Socket clientSocket = listener.Accept();
// Data buffer
byte[] bytes = new Byte[1024];
string data = null;
while (true)
{
int numByte = clientSocket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,
0, numByte);
if (data.IndexOf("<EOF>") > -1)
break;
}
Console.WriteLine("Text received -> {0} ", data);
if(data == "<EOF> " + "kill")
{
Application.Exit();
} else if (data == "<EOF> " + "test")
{
Console.Writeline("It works!");
} else
{
byte[] message = Encoding.ASCII.GetBytes("Error 404 message not found!");
// Send a message to Client
// using Send() method
clientSocket.Send(message);
Messagebox1();
}
// Close client Socket using the
// Close() method. After closing,
// we can use the closed Socket
// for a new Client Connection
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
catch (Exception e)
{
//Console.WriteLine(e.ToString());
}
}
you can use something like this:
this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.clientSocket.Connect(new IPEndPoint(System.Net.IPAddress.Parse(ip), int.Parse(port)));
and pass the ip address to the "ip" variable.
so I have been trying out socket programming in C# using code found online. When looking at this code from https://www.geeksforgeeks.org/socket-programming-in-c-sharp/
public static void ExecuteServer()
{
// Establish the local endpoint
// for the socket. Dns.GetHostName
// returns the name of the host
// running the application.
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
// Creation TCP/IP Socket using
// Socket Class Costructor
Socket listener = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try {
// Using Bind() method we associate a
// network address to the Server Socket
// All client that will connect to this
// Server Socket must know this network
// Address
listener.Bind(localEndPoint);
// Using Listen() method we create
// the Client list that will want
// to connect to Server
listener.Listen(10);
while (true) {
Console.WriteLine("Waiting connection ... ");
// Suspend while waiting for
// incoming connection Using
// Accept() method the server
// will accept connection of client
Socket clientSocket = listener.Accept();
// Data buffer
byte[] bytes = new Byte[1024];
string data = null;
while (true) {
int numByte = clientSocket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,
0, numByte);
if (data.IndexOf("<EOF>") > -1)
break;
}
Console.WriteLine("Text received -> {0} ", data);
byte[] message = Encoding.ASCII.GetBytes("Test Server");
// Send a message to Client
// using Send() method
clientSocket.Send(message);
// Close client Socket using the
// Close() method. After closing,
// we can use the closed Socket
// for a new Client Connection
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
}
}
I was wondering if the portion
while (true) {
int numByte = clientSocket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, numByte);
if (data.IndexOf("<EOF>") > -1)
break;
}
is considered a polling method and also reason why we do not simply use
int numByte = clientSocket.Receive(bytes);
data = Encoding.ASCII.GetString(bytes, 0, numByte);
I have tried the above and it seems to work just as fine. So is there a reason why we use a infinite while loop that depends on the text to stop reading? I have found many sources which seems to use this method. Why is this so?
I have built a server and client which communicate via sockets.
When i run both the server and the client on the same machine both the server and the client receive the messages which are expected.
when i run the server on a VM or a different physical machine and the client on my main machine the server receives messages fine, but the client never receives the reply's
I have made sure to dissable windows firewall and my anti virus on all 3 machines (the 2 physical and one virtual one) to ensure its not a security issue.
The relevant code is as follows
SERVER
public class SynchronousSocketListener
{
// Incoming data from the client.
public static string data = null;
public void StartListening()
{
InstructionProcessor instructionProcessor = new InstructionProcessor();
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true)
{
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
data = data.Substring(0, data.Length - 5);
// Show the data on the console.
string response = instructionProcessor.doSomething(data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(response);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
}
CLIENT
public static string StartClient(string message, string ip)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
//Declare this at class scope level so it can be returned outside of try/catch blocks
string response = null;
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.GetHostEntry(ip);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
//string hostName = Dns.GetHostName();
//string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString(); ;
//Debug.WriteLine( ipAddress );
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(message + "<EOF>");
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
response = Encoding.ASCII.GetString(bytes, 0, bytesRec);
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return response;
}
}
Maybe because client is receiving more than 1024 byte. Try to increase the size of the received buffer.
Also add if (data.IndexOf("") > -1) into the client project.
I am creating a simple networking application that allows one client to connect to the host and sends and recieves data between the two in a while loop. I got most of my code from MSDN, however when I run it, right after Socket.Accept() is called, the form stops running and a TypeInitialization Error is raised. Here is my code:
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, HostingPort);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
Socket handler = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
handler = listener.Accept();
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
byte[] trimmedData = new byte[bytesRec];
Array.Copy(bytes, trimmedData, bytesRec);
string data = Encoding.ASCII.GetString(bytes));
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(foo);
handler.Send(msg);
}
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception) { }
}
This is the function that controls everything. Can you find the error, or if there is a proven way to complete this, I'm fine with starting over from scratch. Thank you in advance.
I want a chat application in C# Client and in Java Server
I go through C# Client but I got some Error when I response to Java Server I get the error#
cannot access a disposed object object name='System.Net.Socket.Socket'
class Program
{
static void Main(string[] args)
{
byte[] bytes = new byte[1024];// data buffer for incoming data
// connect to a Remote device
try
{
// Establish the remote end point for the socket
IPHostEntry ipHost = Dns.Resolve("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 95);
Socket Socketsender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint
Socketsender.Connect(ipEndPoint);
Console.WriteLine("\n\n___________________Client Server Chat Application__________________________");
Console.WriteLine("___________________________________________________________________________");
Console.WriteLine("\nSocket Connecting To Java Server...." + Socketsender.RemoteEndPoint.ToString());
// Console.ReadLine();
string data = null;
while (true)
{
//Recieved from Java Server Message
int bytesRec = Socketsender.Receive(bytes);
Console.WriteLine("\nJava Server:: {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Console.ReadLine();
Console.Write("C# Client ::"); // Prompt
string line = Console.ReadLine();
byte[] sendToServer = Encoding.ASCII.GetBytes(line);
// Send the data through the socket
int intByteSend = Socketsender.Send(sendToServer);
// Socketsender.Shutdown(SocketShutdown.Both);
Socketsender.Close();
Console.WriteLine("____________________________________________________________________________");
Console.WriteLine("_________________________End Chat___________________________________________");
// Socketsender.Shutdown(SocketShutdown.Both);
Socketsender.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
You are closing your socket (Socketsender) in he while loop, and then—in the next iteration—calling Receive on it.
Once a socket is closed it is dead,1 and cannot be used for anything. You would need to create a new socket and connect it to the server.
Or better, keep the first socket open.
(You also are performing the close twice, but I'm assuming that is a transcription error.)
1 Insert dead parrot here.