I wrote a server-client chat LAN app for windows PC using class TcpClient. It worked then I wanted to put Client app chat on android thanks to xamarin,
to connect PC and mobile.
Connecting process works:
private void buttonClickConnect(object sender, EventArgs e)
{
client = new TcpClient();
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.1.1"), int.Parse("13000"));
try
{
client.Connect(IP_End);
if (client.Connected)
{
textviewConversation.Text += "Connected to server" + "\n";
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
worker1.RunWorkerAsync();
worker2.WorkerSupportsCancellation = true;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
it connects to the server, but I cannot send messages. After the second message app crashes, it reads that thread is busy.
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
if (client.Connected)
{
STW.WriteLine(text_to_send);
}
else
{
Console.WriteLine("send failed !");
}
worker2.CancelAsync();
}
There is no loop and the thread should just send it and and not block afterwards.
Find the full code here.
Related
I am battling to connect to a website using udpclient. Whenever I connect to localhost, I have no problems. This is the code I am using :'
private void button1_Click(object sender, EventArgs e)
{
UdpClient udpClient = new UdpClient();
udpClient.Connect("www.ituran.com/ituranmobileservice/mobileservice.asmx", 45004);
Byte[] btSendData = Encoding.ASCII.GetBytes("TESTING");
udpClient.Send(btSendData, btSendData.Length);
}
public void serverThread()
{
try
{
UdpClient udpClient = new UdpClient(45004);
while (true)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] btRecieve = udpClient.Receive(ref RemoteIpEndPoint);
string strReturnData = Encoding.ASCII.GetString(btRecieve);
Console.WriteLine(RemoteIpEndPoint.Address.ToString() + ":" + strReturnData.ToString());
}
}
catch (Exception ex)
{
using (StreamWriter sw = new StreamWriter("TEST_errorLog.txt", true))
{
sw.WriteLine();
sw.WriteLine(ex.ToString());
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Thread thdUDPServer = new Thread(new ThreadStart(serverThread));
thdUDPServer.IsBackground = true;
thdUDPServer.Start();
}
The people that sent me the URL has confimed five times that the address and port is correct. How can I connect to that address?
Any help would be appreciated.
Change the host name to just www.ituran.com. There are no paths in UDP - you are just sending packets to a port on a server.
I have an embedded system, and I want to send and receive information on it using UDP on C#. And I can't make my program to receive completely valid UDP packet.
Embedded system waits for a UDP packet to port 57301, sent from port 57301 (not the arbitrary one!) and then answers to port 57311 from port 57311. Wireshark shows me completely valid packets from computer to embedded system and from embedded system to computer, but C# program doesn't want to see it.
// Button handler, I press it to send message
private void SendUDP_Click(object sender, EventArgs e)
{
Send();
}
// Button handler, I press it before sending anything just to start receiver
private void button1_Click(object sender, EventArgs e)
{
StartReceive();
}
// Sending completely as planned
void Send()
{
UdpClient udp = new UdpClient(57301);
byte[] message = Encoding.Default.GetBytes(Message.Text);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.0.14"), 57301);
udp.Send(message, message.Length, ep);
udp.Close();
}
void StartReceive()
{
ThreadStart tstart = new ThreadStart(Receive);
workReceive = new Thread(tstart);
workReceive.Start();
}
bool stopReceive = false;
Thread workReceive = null;
UdpClient udp = null;
void Receive()
{
ShowMessage("Receive started");
try
{
IPEndPoint ep = new IPEndPoint(IPAddress.Any, 57311);
udp = new UdpClient(ep);
while (true)
{
IPEndPoint remote = null;
byte[] message = udp.Receive(ref remote); // <--- NEVER RECEIVE ANYTHING!
ShowMessage("Received!");
if (stopReceive == true) break;
}
}
catch (Exception e)
{
ShowMessage("Exception!");
}
finally
{
if (udp != null) udp.Close();
}
}
Any suggestions where the problem is?
UPD: The problem were in embedded system: wrong UDP checksum calculation routine - don't know why I thought that it should be the same as ip4 routine.
I want to send a message from a C# application to the Android emulator or device over TCP. I have searched on Google and got the maximum results for Android client and C# server but not what I want to acheive.
Here is what I have tried; maybe I am going about it the wrong way but what I want is to send a message over TCP to an Android device.
Server Code to send a message:
private static int port = 4444;
private static TcpListener listener;
private static Thread thread;
private static int clientId = 0;
listener = new TcpListener(new IPAddress(new byte[] { 127, 0, 0, 1 }), port);
thread = new Thread(new ThreadStart(Listen));
thread.Start();
private static void Listen()
{
listener.Start();
MessageBox.Show("Listening on: " + port.ToString());
while (true)
{
MessageBox.Show("Waiting for connection....");
MessageBox.Show("Client No: " + clientId);
TcpClient client = listener.AcceptTcpClient();
Thread listenThread = new Thread(new ParameterizedThreadStart(ListenThread));
listenThread.Start(client);
}
}
private static void ListenThread(Object client)
{
NetworkStream netstream = ((TcpClient)client).GetStream();
MessageBox.Show("Request made");
clientId = clientId + 1;
// String message = "Hello world";
byte[] resMessage = Encoding.ASCII.GetBytes(clientId.ToString());
netstream.Write(resMessage, 0, resMessage.Length);
netstream.Close();
}
Client Code
private TextView textDisplay;
Socket socket;
private static final int TCP_SERVER_PORT = 4444;
ServerSocket ss = null;
try {
ss = new ServerSocket(TCP_SERVER_PORT);
//ss.setSoTimeout(10000);
//accept connections
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//receive a message
String incomingMsg = in.readLine() + System.getProperty("line.separator");
Log.d("TcpServer", "received: " + incomingMsg);
textDisplay.append("received: " + incomingMsg);
//send a message
String outgoingMsg = "goodbye from port " + TCP_SERVER_PORT + System.getProperty("line.separator");
out.write(outgoingMsg);
out.flush();
Log.d("TcpServer", "sent: " + outgoingMsg);
textDisplay.append("sent: " + outgoingMsg);
//SystemClock.sleep(5000);
s.close();
} catch (InterruptedIOException e) {
//if timeout occurs
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
Log.d("Error",e.toString());
}
}
}
The problem lies in your Client code.
A socket is opened between two parties, one that plays the role of the listener / server that does bind->listen->accept and a client that connect
In your code there are two problems:
Your client should connect and not accept
Both your client and your server will try to read from the socket and write afterwards. There would be no problem if your read and write operations from the socket were on different threads.In your case this will result in a deadlock.
If you want both operations to be done on the same thread , sequentially then your client and server should perform the read and write in opposite order :
Client : read -> write
Server: write-> read
I am making a program in 2 parts.
Part 1: C# server-socket Application running on PC, listening for commands, and acts accordingly.
Part 2: Java client-socket application running on phone, that sends a command to the pc, when a button is pressed.
Currently, i can send commands from the client to the server, and its all good.
But my problem is this: When i send a specific command to the server, i want the server to reply to the client, and the client to read that reply.
Thing just is, when the client tries to read, it time-outs.
Java client program:
class ClientThread implements Runnable
{
public void run()
{
try
{
Socket socket = new Socket(serverIpAddress, serverPort);
socket.setSoTimeout(5000);
while (true)
{
try
{
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.d("Nicklas", "Out it goes");
out.println(Command);
if (Command == "CMD:GetOptions<EOF>")
{
Log.d("Nicklas", "Getting options");
try
{
Log.d("Nicklas", "Line 1");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d("Nicklas", "Line 2");
String answer = in.readLine();
Log.d("Nicklas", "answer = " + answer );
}
catch (Exception ee)
{
Log.d("Nicklasasasas", ee.toString());
}
}
break;
}
catch (Exception e)
{
Log.d("Nicklas", "CAE = " + e.toString());
break;
}
}
socket.close();
}
catch (ConnectException ee)
{
Log.d("Nicklas", "Kunne ikke forbinde");
}
catch (Exception e)
{
Log.d("Nicklasssssss", e.toString());
}
}
}
This is called with:
Thread cThread = new Thread(new ClientThread());
cThread.start();
And uses the global variable "Command", which will contain different information, depending on what button was pressed.
The program fails on the line "String answer = in.readline();" with the exception "java.net.SocketTimeoutException".
This is the C# Server part of the program:
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
//System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
string Input = (encoder.GetString(message, 0, bytesRead));
Input = Input.Trim();
object[] obj = new object[1];
obj[0] = Input;
if (Input == "CMD:GetOptions<EOF>")
{
try
{
byte[] buffer = encoder.GetBytes("CMD:Accepted");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
MessageBox.Show("Client program asked for reply");
}
catch (Exception e)
{
MessageBox.Show("Oh it no work!: " + e.ToString());
}
}
else
{
Udfor(Input);
}
}
tcpClient.Close();
}
Called with the following, in the Form1()
this.tcpListener = new TcpListener(IPAddress.Any, 4532);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
The C# Server seems to work fine, and does show the messagebox "client program asked for reply"
Anyone who can spot the error?
I figured it out!
The problem was the C#. When the server sent back the command "CMD:Accepted", it never closed the socket, so the android application had no idea of telling if it was done reading! Closing the socket right after flushing + of course not closing it again if i already did, did the trick!
I'm new to Android programming and I'm trying to send some text data to PC via TCP.
I built an example I found on the web, which has an Android Client and a Java Server.
The server runs ok.
When I run the Android Client on the emulator or on the phone, both works perfectly well.
The problem is that I need it to communicate to a C# application, so I built an TCP server in C#.
Now, if I run the Client on the emulator it works and the C# server receive the data (a little messed, but it's probably an text encoding problem which I think won't be hard to solve). But anyway, the data is arriving at the c# server.
If I try to run the same Client on the phone I can't even connect to the C# server. I get a timeout error when connecting.
Also I can ping the PC from phone and ping the phone from PC, so I don't think it's a network problem.
I have some experience in C# but not much on sockets and even less on Android. So I ask, is there any difference on TCP protocols used by Java and C#? Sorry if it's a dumb question, but I googled it for hours and haven't found a clue.
Any ideas of what may be causing it?
The Java server code is this:
public class Servidor {
private static boolean executando = true;
private static String mensagem;
private static final int PORTA = 1234;
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(1234);
InetAddress addr = InetAddress.getLocalHost();
System.out.println("----------- SERVER CONNECTED "
+ addr.getHostAddress() + " PORT " + PORTA
+ " -----------");
System.out.println("Waiting connections.");
Socket socket = server.accept();
System.out.println("Server -> Connected Ip "
+ socket.getInetAddress().getHostAddress());
DataInputStream in = new DataInputStream(socket.getInputStream());
try {
while (executando) {
mensagem = in.readUTF();
System.out.println("Server-> Received Message: "
+ mensagem);
}
System.out.println("Servidor-> Finalizado.");
in.close();
socket.close();
server.close();
} catch (Exception e) {
System.err.println("Server -> Error: " + e.getMessage());
executando = false;
}
} catch (Exception e) {
e.printStackTrace();
}
} }
The C# Server code is this:
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
Console.WriteLine("\nStarting server...");
this.tcpListener = new TcpListener(IPAddress.Any, 1234);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
Console.WriteLine("\nWaiting for clients to connect...");
this.tcpListener.Start();
while (true)
{
blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
create a thread to handle communication
with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
Console.WriteLine("\nIncoming from client...");
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
a socket error has occured
break;
}
if (bytesRead == 0)
{
the client has disconnected from the server
break;
}
message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine("\nReceived: \n\n" + encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
}
If needed, the Android Client code is exactly the one on the following link:
http://www.portalandroid.org/comunidade/viewtopic.php?f=7&t=11077&p=127577