I'm trying to create this simple client-server. I have an android client and c#server. just a simple program that sends a hello message to the server but the message isn't sent.
my java code:
Thread t= new Thread()
{
#Override
public void run() {
// TODO Auto-generated method stub
try {
Socket myClient= new Socket("192.167.01.123",7000);
DataOutputStream dos= new DataOutputStream(myClient.getOutputStream());
dos.writeBytes("Hello");
dos.flush();
dos.close();
myClient.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
System.out.println("unknown host");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("IOExxception");
}
}
};
t.start();
Toast.makeText(this," Message sent" , Toast.LENGTH_SHORT).show();
}
and c# code:
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(7000);
TcpClient clientSocket = new TcpClient();
serverSocket.Start();
Console.WriteLine("Server started.");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine("Accept conns from client.");
while (true)
{
try
{
NetworkStream networkStream = clientSocket.GetStream();
Byte[] bytes = new Byte[10025];
networkStream.Read(bytes, 0, (int)clientSocket.ReceiveBufferSize);
string dataClient = System.Text.Encoding.ASCII.GetString(bytes);
Console.WriteLine("data from client: " + dataClient);
networkStream.Flush();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine("EXIT");
Console.ReadKey();
}
}
}
Should be inside the while loop
clientSocket = serverSocket.AcceptTcpClient();
Try this:
c# Server Class to Receive Message :
class Server
{
int BUFSIZE = 100;
int servPort = 1551;
public static String ClientOrder = "";
public static int bytesRcvd;
public void RunServer()
{
TcpListener listener = null;
TcpClient client = null;
NetworkStream netStream = null;
listener = new TcpListener(IPAddress.Any, servPort);
listener.Start();
byte[] rcvBuffer = new byte[BUFSIZE];
while (true)
{
client = listener.AcceptTcpClient(); // Get clien
netStream = client.GetStream();
{
rcvBuffer = new byte[BUFSIZE];
bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length);
ClientOrder = (Encoding.ASCII.GetString(rcvBuffer)).Substring(0, bytesRcvd);
netStream.Close();
client.Close();
}
}
}
}
Android Client Class to Send Message:
public class Send_Message_To_Server implements Runnable {
private String mMsg,Server;
private Socket client;
private PrintWriter printwriter;
public Send_Order_To_Server(String msg,String IP) {
mMsg = msg;
Server=IP;
}
public void run() {
try {
client = new Socket(Server, 1551); //connect to server
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(mMsg); //write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); //closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
I am trying to create a async socket server but it does not wait for a client to connect and exits
class Program
{
IPAddress ipadd;
int port;
TcpListener tcplistener;
public async void startListeningForConnection(IPAddress ip = null, int dport = 23000)
{
if (ip == null)
{
ip = IPAddress.Any;
}
if (dport <= 0)
{
dport = 23000;
}
ipadd = ip;
port = dport;
tcplistener = new TcpListener(ipadd, port);
try
{
tcplistener.Start();
Console.WriteLine("Ready to accept client request.");
while (true)
{
TcpClient clientResponse =await tcplistener.AcceptTcpClientAsync();
HandleClientRequest(clientResponse);//method displays the message from client
}
}
catch (Exception ex)
{
Console.WriteLine("Exception occured: {0}", ex.ToString());
}
}
private void HandleClientRequest(TcpClient acceptReturn)
{
NetworkStream stream = null;
StreamReader reader = null;
try
{
stream = acceptReturn.GetStream();
reader = new StreamReader(stream);
char[] buff = new char[64];
Console.WriteLine("***Ready to read");
while (true)
{
int nRet = reader.Read(buff, 0, buff.Length);
if (nRet == 0)
{
Console.WriteLine("Socket disconnected");
break;
}
string receivedText = new string(buff);
Console.Write(receivedText);
Array.Clear(buff, 0, buff.Length);
stream.Flush();
}
stream.Close();
}
catch (Exception ex)
{
Console.WriteLine("Unknown Exception: {0}", ex.ToString());
}
finally
{
tcplistener.Stop();
Console.WriteLine("Exiting");
}
}
When i run startListeningForConnection(), I get this:
Output:
Ready to accept client request.
Press any key to continue . . .
it does not wait for a client to connect. If I remove the async and await then the program works as intended. Can anyone help me as it is my first socket program.
I need to develop a software that catch all alarm alerts from a Sur-Gard System 1.
For now I created this tcp listener en c# and works fine using my phone as a client but it does not stablish communication with the Sur-Gard, I pingued to the sur-gard IP and there is communication between them, and I'm sure that the port it's correct.
What I'm doing wrong?
static void Main(string[] args)
{
Reconect:
System.Net.Sockets.TcpListener server = null;
try
{
Int32 port = 1025;
server = new System.Net.Sockets.TcpListener(IPAddress.Any, port);
server.Start();
while (true)
{
Console.WriteLine($#"Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(ThreadProc, client);
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
server.Stop();
}
goto Reconect;
}
private static void ThreadProc(object obj)
{
var client = (TcpClient)obj;
Console.WriteLine("Connected!");
Byte[] bytes = new Byte[1024];
String cadena_obtenida = null;
cadena_obtenida = null;
NetworkStream stream = client.GetStream();
int i;
try
{
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
cadena_obtenida = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Alerta recibida: {0}", cadena_obtenida);
byte[] respuesta = System.Text.Encoding.ASCII.GetBytes("El servidor ha recibido: " + cadena_obtenida + Environment.NewLine);
stream.Write(respuesta, 0, respuesta.Length);
stream.Flush();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
client.Close();
}
My Client Source Code :
public partial class Form1 : Form
{
string serverip = "localHost";
int port = 160;
public Form1()
{
InitializeComponent();
}
private void Submit_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient(serverip, port);
int byteCount = Encoding.ASCII.GetByteCount(Message.Text);
byte[] sendData = new byte[byteCount];
sendData = Encoding.ASCII.GetBytes(Message.Text);
NetworkStream stream = client.GetStream();
stream.Write(sendData, 0, sendData.Length);
stream.Close();
client.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
My server
class Program
{
static void Main(string[] args)
{
IPAddress ip = Dns.GetHostEntry("localHost").AddressList[0];
TcpListener server = new TcpListener(ip, 160);
TcpClient client = default(TcpClient);
try
{
server.Start();
Console.WriteLine("The server has started successfully");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
while (true)
{
client = server.AcceptTcpClient();
byte[] receivedBuffer = new byte[100];
NetworkStream stream = client.GetStream();
stream.Read(receivedBuffer, 0, receivedBuffer.Length);
StringBuilder msg = new StringBuilder();
foreach (byte b in receivedBuffer)
{
if (b.Equals(59))
{
break;
}
else
{
msg.Append(Convert.ToChar(b).ToString());
}
}
Console.WriteLine(msg.ToString() + msg.Length);
}
}
}
Essentially i want make it so i can have multiple clients on the server sending a message from different ip addresses of course. I have been using c# a year now mostly in school and I am above average at best at it.
First time asking question so sorry if its in wrong format
I have a little application which sends images from client to all other clients. Actually my buffer size is set to 4096. But I need to have a dynamic size, so that I can send larger images.
Any one of you have an idea what I have to change in my code?
Here is the full code (server and client are in one app):
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
namespace TCPClientServer
{
public partial class Main : Form
{
private Socket clientSocket; //The main client socket
private byte[] clientData = new byte[4096];
private List<Socket> clientSockets = new List<Socket>();
Socket serverSocket; //The main socket on which the server listens to the clients
byte[] serverData = new byte[4096];
public Main()
{
InitializeComponent();
}
#region AsyncCallback
#region ClientCallbacks
private void OnConnect(IAsyncResult result)
{
try
{
clientSocket.EndConnect(result);
clientData = new byte[4096];
//Start listening to the data asynchronously
clientSocket.BeginReceive(clientData, 0, clientData.Length, SocketFlags.None, new AsyncCallback(OnClientReceive), null);
MessageBox.Show("Verbindung wurde hergestellt.");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void OnClientSend(IAsyncResult result)
{
try
{
clientSocket.EndSend(result);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void OnClientReceive(IAsyncResult result)
{
try
{
clientSocket.EndReceive(result);
Image msgReceived = ByteToImage(clientData);
pictureBox1.Image = msgReceived;
clientData = new byte[4096];
clientSocket.BeginReceive(clientData, 0, clientData.Length, SocketFlags.None, new AsyncCallback(OnClientReceive), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
#endregion
#region ServerCallbacks
private void OnAccept(IAsyncResult result)
{
try
{
Socket client = serverSocket.EndAccept(result);
// save new client into clientlist
clientSockets.Add(client);
//Start listening for more clients
serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
//Once the client connects then start receiving the commands from her
client.BeginReceive(serverData, 0, serverData.Length, SocketFlags.None, new AsyncCallback(OnServerReceive), client);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public void OnServerSend(IAsyncResult result)
{
try
{
Socket client = (Socket) result.AsyncState;
client.EndSend(result);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void OnServerReceive(IAsyncResult result)
{
try
{
Socket client = (Socket) result.AsyncState;
client.EndReceive(result);
//Transform the array of bytes received from the user
Image msgReceived = ByteToImage(serverData);
pictureBox1.Image = msgReceived;
//Send the message to all users
foreach (Socket socket in clientSockets)
{
socket.BeginSend(serverData, 0, serverData.Length, SocketFlags.None, new AsyncCallback(OnServerSend), socket);
}
serverData = new byte[4096];
//Start listening to the message send by the user
client.BeginReceive(serverData, 0, serverData.Length, SocketFlags.None, new AsyncCallback(OnServerReceive), client);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
#endregion
#endregion
private void btn_Client_Click(object sender, EventArgs e)
{
try
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
//Server is listening on port 15973
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 15973);
//Connect to the server
clientSocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null);
btn_Client.Enabled = false;
btn_Server.Enabled = false;
btn_Send.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btn_Server_Click(object sender, EventArgs e)
{
try
{
//We are using TCP sockets
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Assign the any IP of the machine and listen on port number 15973
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 15973);
//Bind and listen on the given address
serverSocket.Bind(ipEndPoint);
serverSocket.Listen(4);
//Accept the incoming clients
serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
btn_Client.Enabled = false;
btn_Server.Enabled = false;
btn_Send.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btn_Send_Click(object sender, EventArgs e)
{
try
{
Image img = new Bitmap(#"C:\Users\Kai\Desktop\microsoft-windows-10-icon.png");
clientData = ImageToByte(img);
clientSocket.BeginSend(clientData, 0, clientData.Length, SocketFlags.None, new AsyncCallback(OnClientSend), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[]) converter.ConvertTo(img, typeof(byte[]));
}
private Image ByteToImage(byte[] bytes)
{
ImageConverter converter = new ImageConverter();
return (Image) converter.ConvertFrom(bytes);
}
}
}
Thx in advance :)
This might help.
private int getImageBufferLength(Image image)
{
MemoryStream mStream = new MemoryStream();
image.Save(mStream, image.RawFormat);
int length = mStream.ToArray().Length;
mStream.Dispose();
return length;
}
i'm trying to write simple tcp\ip client-server.
here is server code:
internal class Program
{
private const int _localPort = 7777;
private static void Main(string[] args)
{
TcpListener Listener;
Socket ClientSock;
string data;
byte[] cldata = new byte[1024];
Listener = new TcpListener(_localPort);
Listener.Start();
Console.WriteLine("Waiting connections [" + Convert.ToString(_localPort) + "]...");
try
{
ClientSock = Listener.AcceptSocket();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
int i = 0;
if (ClientSock.Connected)
{
while (true)
{
try
{
i = ClientSock.Receive(cldata);
}
catch
{
}
try
{
if (i > 0)
{
data = Encoding.ASCII.GetString(cldata).Trim();
ClientSock.Send(cldata);
}
}
catch
{
ClientSock.Close();
Listener.Stop();
Console.WriteLine(
"Server closing. Reason: client offline. Type EXIT to quit the application.");
}
}
}
}
}
And here is client code:
void Main()
{
string data; // Юзерская дата
byte[] remdata ={ };
TcpClient Client = new TcpClient();
string ip = "127.0.0.1";
int port = 7777;
Console.WriteLine("\r\nConnecting to server...");
try
{
Client.Connect(ip, port);
}
catch
{
Console.WriteLine("Cannot connect to remote host!");
return;
}
Console.Write("done\r\nTo end, type 'END'");
Socket Sock = Client.Client;
while (true)
{
Console.Write("\r\n>");
data = Console.ReadLine();
if (data == "END")
break;
Sock.Send(Encoding.ASCII.GetBytes(data));
Sock.Receive(remdata);
Console.Write("\r\n<" + Encoding.ASCII.GetString(remdata));
}
Sock.Close();
Client.Close();
}
When i'm sending to my server i cannt receive data back answer. Sock.Receive(remdata) returns nothing! Why?
You're trying to receive to an empty buffer. You should allocate the buffer with a sensible size, and then take note of the amount of data received:
byte[] buffer = new byte[1024];
...
int bytesReceived = socket.Receive(buffer);
string text = Encoding.ASCII.GetString(buffer, 0, bytesReceived);
(It's somewhat unconventional to use PascalCase for local variables, by the way. I'd also urge you not to just catch Exception blindly, and not to swallow exceptions without logging them.)