im currently making an application where a host makes a TCP connection to me sends me some data, then i read it and send some other data back, but after that (10 seconds) my host informs me that "TCP connection timeout". Its not alot of info but im about 90% sure that its beacuse im not creating a stable TCP connection and im somehow closing it, since im just listening and creating a network stream, but im hoping someone abit more experienced in TCP can be my savior
my code:
public static void ExampleForStackOverFlow()
{
TcpListener listener = new TcpListener(IPAddress.Parse("10.100.202.15"), 52000);
listener.AllowNatTraversal(true);
listener.Start();
while (true)
{
client = listener.AcceptTcpClient();
Console.WriteLine("Client accepted." + listener.Pending());
NetworkStream stream = client.GetStream();
IPEndPoint FLEXSERVER = (IPEndPoint)client.Client.RemoteEndPoint;
try
{
Console.WriteLine("request Translated: ");
RespondForStackOverFlow(stream);
}
catch (Exception e)
{
Console.WriteLine("Something went wrong. " + e.ToString());
}
}
}
public static void RespondForStackOverFlow(NetworkStream stream)
{
try
{
stream.Write(DataToSend, 0, DataToSend.Length);
Console.WriteLine("Sending data");
stream.Flush();
}
catch (Exception e)
{
Console.WriteLine("Something went wrong. " + e.ToString());
}
}
Related
I created a project in c# to simulate a tcp client in c# using visual studio 2017 to understand how TCP/IP communications work at a very high level.
The problem is that the code bellow is throwing an exception "No connection could be made because the target computer actually refused 127.0.0.1:1080"
namespace SimpleTcpEchoClient
{
public class Program
{
static void Main(string[] args)
{
TcpClient ourTcpClient = null;
NetworkStream networkStream = null;
try
{
//initiate a TCP client connection to local loopback address at port 1080
ourTcpClient = new TcpClient();
ourTcpClient.Connect(new IPEndPoint(IPAddress.Loopback, 1080)); //HERE IS WHERE THE EXCEPTION IS THROWN
Console.WriteLine("Connected to server....");
//get the IO stream on this connection to write to
networkStream = ourTcpClient.GetStream();
//use UTF-8 and either 8-bit encoding due to MLLP-related recommendations
var messageToTransmit = "Hello from Client";
var byteBuffer = Encoding.UTF8.GetBytes(messageToTransmit);
//send a message through this connection using the IO stream
networkStream.Write(byteBuffer, 0, byteBuffer.Length);
Console.WriteLine("Data was sent data to server successfully....");
var bytesReceivedFromServer = networkStream.Read(byteBuffer, 0, byteBuffer.Length);
// Our server for this example has been designed to echo back the message
// keep reading from this stream until the message is echoed back
while (bytesReceivedFromServer < byteBuffer.Length)
{
bytesReceivedFromServer = networkStream.Read(byteBuffer, 0, byteBuffer.Length);
if (bytesReceivedFromServer == 0)
{
//exit the reading loop since there is no more data
break;
}
}
var receivedMessage = Encoding.UTF8.GetString(byteBuffer);
Console.WriteLine("Received message from server: {0}", receivedMessage);
Console.WriteLine("Press any key to exit program...");
Console.ReadLine();
}
catch (Exception ex)
{
//display any exceptions that occur to console
Console.WriteLine(ex.Message);
}
finally
{
//close the IO strem and the TCP connection
networkStream?.Close();
ourTcpClient?.Close();
}
}
}
}
I already tried to change the port but without success!
Can someone please help me?
It is solved now, my server was running on port 1081 instead of 1080 :)
i'm trying to make an application which allows the connection between 2 PCs(i planned on making it multi threaded later but lets keep it more simple at the beginning). This could be either used for chatting or sending data to the other pc and he does something to the data and sends it back.
This is my coding so far:
Server:
class Program
{
private static StreamWriter serverStreamWriter;
private static StreamReader serverStreamReader;
private static bool StartServer()
{
//setting up Listener
TcpListener tcpServerListener = new TcpListener(IPAddress.Any, 56765);
tcpServerListener.Start();
Console.WriteLine("Server Started!");
Console.WriteLine("Waiting for Connection...");
Socket serverSocket = tcpServerListener.AcceptSocket();
try
{
if (serverSocket.Connected)
{
Console.WriteLine("Client connected to Server!");
//open network stream on accepted socket
NetworkStream serverSockStream = new NetworkStream(serverSocket);
serverStreamWriter = new StreamWriter(serverSockStream);
serverStreamReader = new StreamReader(serverSockStream);
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
return false;
}
return true;
}
static bool once = false;
static void Main(string[] args)
{
//Set Console Window Stuff
Console.Title = "Server";
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Green;
Console.BufferWidth = 120;
Console.Clear();
//Start Server
if (!StartServer())
Console.WriteLine("Error while Starting Server!");
//Waiting till Client sends Something
while (true)
{
string data = "Append Something to Me - ";
if (!once)//that check -.-
{
serverStreamWriter.WriteLine(data);
serverStreamWriter.Flush();
once = true;
}
Console.WriteLine("Client: " + serverStreamReader.ReadLine());
if (serverStreamReader.ReadLine() != data)
{
serverStreamWriter.WriteLine(data);
serverStreamWriter.Flush();
}
}
}
}
Client:
class Program
{
private static StreamReader clientStreamReader;
private static StreamWriter clientStreamWriter;
private static bool ConnectToServer()
{
try
{
TcpClient tcpClient = new TcpClient("127.0.0.1", 56765);
Console.WriteLine("Connected to Server!");
NetworkStream clientSockStream = tcpClient.GetStream();
clientStreamReader = new StreamReader(clientSockStream);
clientStreamWriter = new StreamWriter(clientSockStream);
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
return false;
}
return true;
}
private static void SendToServer(string message)
{
try
{
clientStreamWriter.WriteLine(message);
clientStreamWriter.Flush();
}
catch (Exception se)
{
Console.WriteLine(se.StackTrace);
}
}
static void Main(string[] args)
{
//Set Console Window Stuff
Console.Title = "Client";
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Red;
Console.BufferWidth = 120;
Console.Clear();
if (!ConnectToServer())
Console.WriteLine("Error while Connecting to Server!");
SendToServer("Send Me Data...");
//Waiting till Server sends Something
while (true)
{
string response = clientStreamReader.ReadLine();
Console.WriteLine(response + "|| Appending Text...");
response += "Appended Text!";
Console.WriteLine("Sended " + response + " back to server!");
SendToServer(response);
}
}
}
Even though this isn't really good coding, it works for me, BUT the main problem with this is it only works on my local machine. How would i make it so if i run the server app on my pc and my friend runs the client app on his pc those two connect!? Help would be really great since i wasn't able to found a detailed tutorial or such and i only created this Account to ask for help here :)
TcpClient tcpClient = new TcpClient("localhost", 3333);
Instead of "localhost", use the remote machine's address here.
Edit:
You don't seem to understand how this connection process works, so I'll try to explain it a little better.
Your server is opening up a socket on port 3333, listening for any connections. This process does not need any external IP adress.
You clients are trying to connect to the server. They need to know what server they're connecting to, so you need to supply them with an IP address. An example would be something like
TcpClient tcpClient = new TcpClient("127.0.0.1", 3333);
//this is identical to using "localhost"
There's no way for you to get around at some point using a remote address in the connection protocol. You can't just tell the client "connect on port 3333" and expect it to know exactly where it needs to connect.
The comment explaining how to resolve a local IP address isn't useful in your case, because what you ended up doing was just telling the client to connect to itself, as you resolved the client's IP address and tried to connect to that.
However, you can have multiple clients connect to the same server. In this case you won't need multiple remote IP addresses, you just tell all the clients to connect to the same remote address and then handle that on the server. This is where the RemoteEndPoint comes into effect.
At the server level you can use the RemoteEndPoint to find the IP address of the clients connecting to it, and use this IP address to return information to those clients.
All in all, you WILL have to use some hardcoded address for your initial
TcpClient tcpClient = new TcpClient(address, 3333);
step. There's no way around this.
I'm really confused. I am able to connect a TCPClient to a tcp server asynchronously. In my callback I now want to start reading some data, but when I go stream = tcpClient.GetStream(); my program doesn't exactly hang, it just does nothing. It won't go to the next line of the method, but the UI is still running (it's Unity, maybe it is multithreaded or something).
public void SetupSocket() {
try {
tcpClient = new TcpClient(host, port);
tcpClient.BeginConnect(host, port, ConnectCallback, tcpClient);
}
catch (Exception e) {
// stuff happens
return;
}
}
private void ConnectCallback(IAsyncResult result) {
if (ConnectedToServer != null)
ConnectedToServer(this, new ServerEventArgs("Connected to server."));
Debug.Log("Where am I?"); // it does get here
try {
stream = tcpClient.GetStream();
}
catch (InvalidOperationException e){
Debug.Log(e); // no exception
}
Debug.Log("Hello?"); // never gets here
BeginReadData();
}
public void BeginReadData() {
Debug.Log(stream.CanRead); // No log here!
if (stream.CanRead) {
stream.BeginRead(tcpStateObject.buffer, 0, tcpStateObject.bufferSize, EndReadData, stream);
}
}
I'm really lost at this point. I can see on my server that I connected, and when I disconnect. I send two messages to the client. It used to work with synchronous sockets, but I wanted async.
Here is the answer
I was connecting twice
tcpClient = new TcpClient(host, port);
tcpClient.BeginConnect(host, port, ConnectCallback, tcpClient);
I need a socket communication between my own written java server and C# client, the problem is that the C# client can't receive any messages from my java server, but sending messages to my java server works.
my workflow:
Java: Create Server
Java: Waiting for Client connection
c#: Create Client
c#: Build connection to the server
c#: send a msg to the server
Java: msg received
java: send msg to c# client
c#: receiving msg from server <- this is the point where the client waits for a message but never get.
Java Server code:
public class Communicator {
private int m_port;
private Socket m_socket;
private ServerSocket m_serverSocket;
public Communicator(int port) {
this.m_port = port;
initConnection();
}
private void initConnection() {
try {
System.out.println("Creating Server");
m_serverSocket = new ServerSocket(m_port);
System.out.println("Waiting for client connection");
m_socket = m_serverSocket.accept();
System.out.println("Connection made");
} catch (IOException e) {
e.printStackTrace();
}
}
public String sendMsg(JSONMessage msg) {
try {
//get msg
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(m_socket.getInputStream()));
System.out.println("Waiting for msg...");
String answer = bufferedReader.readLine();
System.out.println("Received: " + answer);
//send msg
PrintWriter writer = new PrintWriter(m_socket.getOutputStream(),true);
writer.print(msg.getMsg());
System.out.println("Sending: " + msg.getMsg());
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
My C# client code:
class Communicator
{
private int m_port;
private Thread mainThread;
public Communicator(int port)
{
m_port = port;
mainThread = new Thread(new ThreadStart(this.initConnection));
mainThread.Start();
}
public void initConnection()
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_port);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
Console.WriteLine("Trying to build connection");
server.Connect(ip);
Console.WriteLine("Connection successful");
NetworkStream ns = new NetworkStream(server);
StreamReader sr = new StreamReader(ns);
StreamWriter sw = new StreamWriter(ns);
string data;
string welcome = "Hello";
Console.WriteLine("Sending: " + welcome);
sw.WriteLine(welcome);
sw.Flush();
Console.WriteLine("Receiving...");
data = sr.ReadLine();
// --> NEVER REACHING THIS POINT <---
Console.WriteLine("Received: " + data);
}
catch (SocketException e)
{
Console.WriteLine("Connection failed.");
return;
}
}
}
Does somebody has any idea why it never reaches my client code Console.WriteLine("Received: " + data); ?
I already tried with waits on both sides. I'm not getting any exceptions or error so I don't have really an idea where my problem is.
Thanks
If your receiver is expecting lines, your sender has to send lines. Your sender does not send lines, so the receiver waits forever until it gets one.
To avoid these kinds of problems in the future, you should always make a specification document that explains how your protocol works, ideally at the byte level. It should specify whether the protocol contains messages and if so, how the sender marks message boundaries and how the receiver identifies them.
Here, your receiver identifies message boundaries by looking for line endings. But your sender doesn't mark message boundaries with line endings. So the receiver waits forever.
If you had a protocol specification, this would have been obvious. In the future, I strongly urge you to invest the time to specify every protocol you implement.
You need to use println() which adds a new line instead of print(). In Java, readLine waits for a new line and I would expect it to do the same in C#. Also println will auto-flush, so you don't need to flush as well.
If you intend to use this connection mreo than once, you need to keep the BufferedReader and PrintWriter for the connection. (So I suggest you create these after the socket is created/accepted) Creating these multiple times for the same socket can be error prone and confusing.
I'm a Java Developer Trying to build a Simple C# TCP Client. however for the life of me I can't figure out how to get this bloody thing to work. Here is my TCPClient code. BTW, I stole this directly from msdn. http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx
public static void Connect(String server, int port, String message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("\n Press Enter to continue...");
Console.Read();
}
Here is my Java Server.
private ServerSocket socket;
private JAXBContext jaxbContext;
boolean listening = true;
#SuppressWarnings("unused")
private HMSAgentService() {
}
public HMSAgentService(int port) {
try {
this.socket = new ServerSocket(port);
logger.debug("Agent Service listening on port : " + port);
this.jaxbContext = HMSAgentUtil.getJAXBContext();
while (listening) {
new AgentServiceThread(socket.accept(), jaxbContext).start();
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
} catch (JAXBException e) {
logger.error(e.getMessage(), e);
}
}
It simply starts off a new thread when it receives a client connection.
Now my problem is that The program never moves past the stream.Write(). Also the server never receives the message. Only after I call Stream.close() does the server receive the message. But that essentially closes the connection and the client can't receive any more messages. Why is happening. I've tried using Sockets, StreamWriters, StreamReaders and its the same story.
At this point i'm contemplating using The Asynchronous method, but I'm trying to keep the program as simple as possible, since there is no need for it. Is there anyway of signaling the end of a Write?