Im trying to make a tcp connection between server and client . server is programmed on c# and cliend on java... server is working fine... my problem is in this code:
try {
InetAddress address = InetAddress.getByName("127.0.0.1");
connection = new Socket(address, port);
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
loginInfo = inFromServer.readLine();
System.out.println("username/pass are received");
System.out.println(loginInfo);
connection.close();
} catch (IOException f) {
System.out.println("IOException: " + f);
} catch (Exception g) {
System.out.println("Exception: " + g);
}
The application is blocked and I can't close it any more... until i finish debug from java .
I guess the problem is in loginInfo because im not getting username/pass are received in output .. so any help?
this is the thread that send message from c# :
Thread listener_service = new Thread((ThreadStart)delegate
{
listener.Start();
while (true)
{
s = listener.AcceptSocket();
Console.WriteLine("Connected to !" + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server. \n"));
Console.WriteLine("\nSent Acknowledgement");
continue;
}
});
calling readLine() is blocking call, means your code execution will be blocked until and unless you receive any line from server communication.
use System.Environment.NewLine instead of \n to terminate your line in C# code.
Related
When I send the message to the client and I try to check it with an if statement it doesn't equal to what I sent from the server.
What I want to do is: I want to send the keyword (here it's poop) and check it with an if statement on the client part.
If it finds that keyword with the if statement I want to execute some code.
For example:
Client code:
try {
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("127.0.0.1",8001);
Console.WriteLine("Connected");
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
while(true)
{
byte[] bb=new byte[100];
int k=stm.Read(bb,0,100);
for (int i=0;i<k;i++)
{
var msg = Convert.ToChar(bb[i]).ToString();
if(msg == "poop")
{
Console.WriteLine("Poop executed.");
}
}
}
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
Server code (when the console reads my input I type "poop"):
try {
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
TcpListener myList=new TcpListener(ipAd,8001);
myList.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint );
Console.WriteLine("Waiting for a connection.....");
Socket s=myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
ASCIIEncoding asen=new ASCIIEncoding();
while(true)
{
Console.Write("Msg to send: ");
var f = Console.ReadLine();
s.Send(asen.GetBytes(f));
}
s.Close();
myList.Stop();
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
The problem with your code is that you iterate over the byte array in which you wrote the received data. Therefore the message variable does always contain only one letter of your received message and is therefore never "poop" but "p", "o", "o", "p". To solve this issue you can use System.Text.Encoding to convert your byte array to a string:
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
var msg = System.Text.Encoding.UTF8.GetString(bb, 0, k);
if(msg == "poop")
{
// Do something
}
An even better solution would be to write back your received data into a temporary array until a defined end of string signal is received and only convert the temporary array if you are sure that everything is received.
I have a Listener application which expects a string message for display. I cannot modify this application.
I have to send messages to this listener through my C# client. Both the listener and client are supposed to run on the same PC (local host).
My Code to Connect:
public void ConnectAndSendMessage(string MessageToSend)
{
string localIP = GetIPAddress();
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect(localIP, 2400);
Socket socket = tcpclnt.Client;
bool connectionStatus = socket.Connected;
if (connectionStatus)
{
//Send Message
ASCIIEncoding asen = new ASCIIEncoding();
//string sDateTime = DateTime.Now.ToString();
int SendStatus = socket.Send(asen.GetBytes(MessageToSend + Environment.NewLine));
}
Thread.Sleep(2000);
tcpclnt.Close();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
Problem:
The client application runs fine and send the messages successfully to the Listener. But the problem comes if the client gets crashed (I close the client program) before executing tcpclnt.Close();. In this case, if I restart the Client program again then, I cannot connect to the socket since the application didn’t close the socket in the previous run (crashed run).
How can I reconnect to the listener in this condition?
try this one..
public void ConnectAndSendMessage(string MessageToSend)
{
string localIP = GetIPAddress();
using (System.Net.Sockets.TcpClient tcpclnt = new System.Net.Sockets.TcpClient())
{
try
{
Console.WriteLine("Connecting.....");
tcpclnt.Connect(localIP, 2400);
using (System.Net.Sockets.Socket socket = tcpclnt.Client)
{
if (socket.Connected)
{
//Send Message
System.Text.ASCIIEncoding asen = new System.Text.ASCIIEncoding();
//string sDateTime = DateTime.Now.ToString();
int SendStatus = socket.Send(asen.GetBytes(MessageToSend + Environment.NewLine));
}
System.Threading.Thread.Sleep(2000);
}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
finally
{
if (tcpclnt != null && tcpclnt.Connected)
tcpclnt.Close();
}
}
}
I am looking for some help with communication between my server application and my client.The idea is that my client will listen for a UDP packet, read it and then execute a command based on what it reads.
My issue is that the server sends the packet however the client does nothing.
Here is a snippet of my code:
Client:
public void listen()
{
try
{
MessageBox.Show("");
UdpClient receivingUdpClient = new UdpClient(11000);
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 11000);
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
string[] split = returnData.Split(':');
if (split[0] == "SayHello")
{
MessageBox.show("Hello user","Hello");
}
//Note i have many commands but i shortened it to save room.
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Server:
else if (radioButton4.Checked)
{
UdpClient udpClient = new UdpClient([IP_ADDRESS_HERE], 11000);
body = richTextBox1.Text;
title = textBox1.Text;
Command = "Message" + ":" + body + ":" + title + ":" + 4;
Byte[] sendBytes = Encoding.ASCII.GetBytes(Command);
try
{
udpClient.Send(sendBytes, sendBytes.Length);
}
catch (Exception)
{
Console.WriteLine(e.ToString());
}
}
Just wanted to see if you guys are able to find something I overlooked.
Check your Windows Firewall and verify it's not blocking your Client from opening port 11000.
Control Panel-> System and Security -> Windows Firewall
I got a working server in C# and a working client in Java (Android). It's totally working, but the connection itself is only one-wayed. Only the client can send data to the server. I tried to make the connection two-sided, but the code not working by an unknown reason.
Where I do it wrong?
C#- server
public void SendBack(string message, NetworkStream stream)
{
if (stream.CanWrite)
{
byte[] candy = Encoding.ASCII.GetBytes(message + ";");
stream.Write(candy, 0, candy.Length);
stream.Flush();
Console.WriteLine("[SENT] " + message);
}
else { Console.WriteLine("ERROR! CANNOT WRITE ON NETWORKSTREAM!"); }
}
Java- client
//Creating the stream in the constructor
bReader = new BufferedReader(new InputStreamReader(gSocket.getInputStream()));
new Thread (new Runnable(){
public void run() {
Log.d(TAG, "Started listerner...");
ListenServer();
}
}).start();
//The function itself
private void ListenServer(){
try
{
String inputLine = "";
while (true){
inputLine = bReader.readLine();
if (inputLine != null) Log.d(TAG, "Got: " + inputLine);
}
}
catch (IOException e){ Log.d(TAG, "Could not listen to sever!"); }
}
Edit: forget to mention whats the actual problem... I start the server, behaves like usual, client can send data, which the server can interpret the message. Hoverwer, if the server sends something, the client do nothing. I mean, it does not execute the
Log.d(TAG, "Got: " + inputLine);
code.
It could be that the server is not sending the line-feed and/or carriage-return. BufferedReader.readLine()(link) expects it. You can construct a StreamWriter with the incoming stream, and use one of the WriteLine methods.
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.