I'm trying to write a small client server program. The Server is in C#, and the client is in Java.
Here are the codes:
Server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Server
{
class Program
{
private TcpListener tcpListener;
public static void Main(string[] args)
{
Program program = new Program();
program.StartServer();
while (true) ;
}
private bool StartServer()
{
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
try
{
tcpListener = new TcpListener(ipAddress, 5678);
tcpListener.Start();
tcpListener.BeginAcceptTcpClient(new AsyncCallback(this.ProcessEvents), tcpListener);
Console.WriteLine("Listing at Port {0}.", 5678);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return false;
}
return true;
}
private void ProcessEvents(IAsyncResult asyn)
{
try
{
TcpListener processListen = (TcpListener)asyn.AsyncState;
TcpClient tcpClient = processListen.EndAcceptTcpClient(asyn);
NetworkStream myStream = tcpClient.GetStream();
if (myStream.CanRead)
{
StreamReader readerStream = new StreamReader(myStream);
string myMessage = readerStream.ReadToEnd();
readerStream.Close();
}
myStream.Close();
tcpClient.Close();
tcpListener.BeginAcceptTcpClient(new AsyncCallback(this.ProcessEvents), tcpListener);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
Client:
import java.io.PrintWriter;
import java.net.Socket;
public class Program {
public static void main(String[] args) {
Socket socket;
try {
socket = new Socket( "127.0.0.1", 5678);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.print("Hello world");
writer.flush();
writer.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
But when I try to create a Socket in client, I get this exception:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at Program.main(Program.java:10)
Can anyone tell me what I'm doing wrong here?
updated: I'm running x64 Windows 7 Ultimate, I don't see anything firewall message pop up (I did saw it for server once, which I allowed and set to always allow). I can connect using telenet, no problem with that. Any other suggestion please.
I have finally figured out the problem myself.
The .Net server was by default using ipv6 address, and Java client was using the ipv4 address. To create a ipv4 address use:
TcpListener tcpListener = new TcpListener(IPAddress.Any, 5678);
instead of:
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
TcpListener tcpListener = new TcpListener(ipAddress, 5678);
Related
Currently, I'm programming in C#, I would like to modify the code below to isolate one client connection. so like creating a break-out room from the main pool.
Below are 2 files, one is just the basic standard .NET Framework Console App Program.cs file; the other is the server file. Combined, they both can make a multi-threaded server, but I would like one that allows me to also select a client to connect to in case if I were to create a remote control application as my friend did.
On a side note, I would like to share that I want to be able to connect to a client by entering connect [1,2,3,etc..] into the console.
Answers
If you answer, please put some code, It would really, really help. I learn a lot better by looking att the code rather than reading documentation.
Code
Server.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace TCPServer
{
class Server
{
TcpListener server = null;
int counter = 0;
public Server(string ip, int port)
{
IPAddress localAddr = IPAddress.Parse(ip);
server = new TcpListener(localAddr, port);
server.Start();
StartListener();
}
public void StartListener()
{
try
{
while (true)
{
Console.WriteLine("Waiting for incoming connections...");
TcpClient client = server.AcceptTcpClient();
counter += 1;
Console.WriteLine("Connected to authorized client: {0}", counter);
Thread t = new Thread(new ParameterizedThreadStart(HandleDeivce));
t.Start(client);
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
server.Stop();
}
}
public void HandleDeivce(Object obj)
{
TcpClient client = (TcpClient)obj;
var stream = client.GetStream();
string imei = String.Empty;
string data = null;
Byte[] bytes = new Byte[256];
int i;
try
{
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
string hex = BitConverter.ToString(bytes);
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("{1}: Received: {0}", data, Thread.CurrentThread.ManagedThreadId);
if (data != "auth token")
{
stream.Close();
client.Close();
}
string str = "Device authorization successfull";
Byte[] reply = System.Text.Encoding.ASCII.GetBytes(str);
stream.Write(reply, 0, reply.Length);
Console.WriteLine("{1}: Sent: {0}", str, Thread.CurrentThread.ManagedThreadId);
}
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e.ToString());
client.Close();
}
}
}
}
Program.cs
using System;
using System.Threading;
namespace TCPServer
{
class Program
{
static void Main(string[] args)
{
Thread thread = new Thread(delegate()
{
Server server = new Server("127.0.0.1", 13000);
});
thread.Start();
Console.WriteLine("Server started...");
}
}
}
me and my friends are currently trying to build a chat application with c sharp in visual studio .
while doing that we bumped into the words "client network" and "server network" .
I ve been told that those are two dll files that provides a connection between my client , server and database . Can anyone explain to me what should these dll files contain and how to they contribute to our chat application ( I am still a beginner )
Thank you so much !
According to your description, you want to solve the communication between the client and the server.
I recommend that you use socket to realize the connection between server and client, and
create two DLL files to facilitate program reference.
It will be explained in detail below.
(1) ClientCommunication.dll
1: Establish a Socket object;
2: Use the Connect() method of the socket object to send the connection request to the server with the EndPoint object created above as a parameter;
3: If the connection is successful, use the Send() method of the socket object to send information to the server;
4: Use the Receive() method of the socket object to receive the information sent by the server;
5: Be sure to close the socket after the communication is over
(2) ServerCommunication.dll
1: Establish a Socket object;
2: Bind EndPoint with the Bind() method of the socket object;
3: Use the Listen() method of the socket object to start listening;
4: Accept the connection to the client, use the socket object's Accept() method to create a new socket object for communicating with the requesting client;
5: Use the new socket object to receive and send messages.
ServerCommunication.dll contains ServerSocket.cs
ServerSocket.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ServerCommunication
{
public class ServerSocket
{
static Socket serverSocket;
public static void StartListening(IPAddress ip, int port)
{
serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
IPEndPoint point = new IPEndPoint(ip, port);
serverSocket.Bind(point);
Console.WriteLine("{0}Listen Success", serverSocket.LocalEndPoint.ToString());
serverSocket.Listen(10);
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
Console.ReadLine();
}
static void ListenClientConnect()
{
while (true)
{
Socket clientSocket = serverSocket.Accept();
clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start(clientSocket);
}
}
static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
//clientSocket accept
byte[] result = new byte[1024];
int receiveNumber = myClientSocket.Receive(result);
Console.WriteLine("Receive client{0}news{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}
}
}
ClientCommunication.dll contains ClientSocket.cs
ClientSocket.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ClientCommunication
{
public class ClientSocket
{
static byte[] result = new byte[1024];
public static void StartClient(IPAddress ip, int port)
{
Socket socketClient = new Socket(SocketType.Stream, ProtocolType.Tcp);
IPEndPoint point = new IPEndPoint(ip, port);
try
{
socketClient.Connect(point);
Console.WriteLine("Successfully connected to server!");
}
catch
{
Console.WriteLine("Failed to connect to the server, please press enter to exit!");
return;
}
//clientSocket accept
int receiveLength = socketClient.Receive(result);
Console.WriteLine("Receive server message:{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
// clientSocket send
try
{
Thread.Sleep(1000);
string sendMessage = "client send Message Hellp" + DateTime.Now;
socketClient.Send(Encoding.ASCII.GetBytes(sendMessage));
Console.WriteLine("Send message to server:{0}" + sendMessage);
}
catch
{
socketClient.Shutdown(SocketShutdown.Both);
socketClient.Close();
}
Console.WriteLine("After sending, press enter to exit");
Console.ReadLine();
}
}
}
The specific use is as follows:
Server,cs code:
using ServerCommunication;
using System.Net;
namespace Server
{
class Server
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 8885;
ServerSocket.StartListening(ip,port);
}
}
}
Client.cs code:
using ClientCommunication;
using System.Net;
namespace Client
{
class Client
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 8885;
ClientSocket.StartClient(ip,port);
}
}
}
Operation results:
Server:
Client:
Im new to c# sockets programing and im working on a little project of a server that sends strings for some clients. I made it by modifing MSDN's Synchronous Server and client Socket Example.
When I run the server and the clients on the same computer,they work fine, but when I run the server on a computer and the client on another computer, a socket exception shows on the client(both computers are at the same network).
Now im not sure what to do: port forwarding? change the code?
server code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace textweb
{
class Program
{
static int counter = 0;
static Socket[] _socket = new Socket[2];
static void Main(string[] args)
{
byte[] bytes = new Byte[1024];
//running the server on the local host
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
Console.WriteLine(ipHostInfo.HostName);
IPAddress ipAddress = ipHostInfo.AddressList[0];
Console.WriteLine(ipAddress);
TcpListener listener = new TcpListener(ipAddress, /*MyPort*/);
try
{
listener.Start(10);
Console.WriteLine("Waiting for a connection...");
while (counter < 2)
{
while (!listener.Pending()) { }
while (listener.Pending())
{
_socket[counter] = listener.AcceptSocket();
counter++;
}
}
bool _continue = true;
while (_continue)
{
string m = Console.ReadLine();
byte[] msg = Encoding.ASCII.GetBytes(m);
foreach (Socket soc in _socket)
{
soc.Send(msg);
if (m == "exit")
{
soc.Shutdown(SocketShutdown.Both);
soc.Close();
_continue = false;
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
}
}
client code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace textclient
{
class Program
{
static void Main(string[] args)
{
byte[] bytes = new byte[1024];
try {
IPHostEntry ipHostInfo = Dns.GetHostByName(/*server's ip*/);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress,/*MyPort*/);
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
try {
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",sender.RemoteEndPoint.ToString());
bool _continue = true;
while (_continue)
{
if (sender.Available>0)
{
int bytesRec = sender.Receive(bytes);
string a = Encoding.ASCII.GetString(bytes, 0, bytesRec);
Console.WriteLine(a);
if (a == "exit")
{
sender.Shutdown(SocketShutdown.Both);
sender.Close();
_continue = false;
}
}
}
Console.ReadKey();
} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
Console.ReadKey();
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}", se.ToString());
Console.ReadKey();
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
Console.ReadKey();
}
} catch (Exception e) {
Console.WriteLine( e.ToString());
Console.ReadKey();
}
}
}
}
I hope the question was clear and you will answer it,
Itay
Well, I found a solution very fast.
I just port-forwarded the port im using to the server ip.
for example if server ip is 10.0.0.1 and port is 2222
I just needed to forward port 2222 in with "lan users" 10.0.0.1.
Thank you for your help anyway.
I am trying to get to grips with sockets and it is proving a bit harder than I thought. I have googled this error and have tried to fix it myself by toying with my code but I do not understand what is not right here. The following code is giving me a socket exception with the error "A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied." As you can see I am trying this on my local machine, the client simply connects and sends a string. Any tips or pointers would be nice!
NOTE I have read other similar questions here on Stack Overflow but have not managed to fix my program with the solutions!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Server
{
class Program
{
private static Socket socket = null;
private static Socket client = null;
private static IPAddress ipAddress = null;
private static int port = 1090;
private static IPEndPoint endPoint = null;
private static byte[] buffer;
private static int socketRecv = 0;
static void Main(string[] args)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ipAddress = IPAddress.Parse(GetLocalIPv4(NetworkInterfaceType.Ethernet));
endPoint = new IPEndPoint(ipAddress, port);
buffer = new byte[1024];
Console.WriteLine("\nVariables initialized...");
socket.Bind(endPoint);
socket.Listen(5);
Console.WriteLine("\nSocket bound and listening...");
client = socket.Accept();
Console.WriteLine("\nSocket accepted connection...");
//the program gets to here, then the exception is thrown
while (true)
{
if (socketRecv == 0)
{
socketRecv = socket.Receive(buffer);
continue;
}
Console.WriteLine("\nData wrote...\n");
break;
}
Console.WriteLine(System.Text.Encoding.Default.GetString(buffer));
Console.Read();
}
public static string GetLocalIPv4(NetworkInterfaceType _type)
{
string output = "";
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up)
{
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
output = ip.Address.ToString();
}
}
}
}
return output;
}
}
}
I wrote a C# TCP Server that runs on my desktop, while I have a client running on my windows phone. It works great, the client can connect to the server. But I am trying to make it so the server can receive messages from the client. When I run it, the server just receives a number when I am sending a string.
Here is my server code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;
namespace TCPServer
{
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Any, 80);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
TcpClient client = this.tcpListener.AcceptTcpClient();
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
Console.WriteLine("Got connection");
StreamReader clientStreamReader = new StreamReader(clientStream);
Console.WriteLine(clientStreamReader.Read());
}
}
}
Here is the client code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace NetworkingTesting
{
class Client
{
Socket socket = null;
static ManualResetEvent clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 5000;
const int MAX_BUFFER_SIZE = 2048;
DnsEndPoint hostEntry;
public string Connect(string hostName, int portNumber)
{
string result = string.Empty;
hostEntry = new DnsEndPoint(hostName, portNumber);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = hostEntry;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
result = e.SocketError.ToString();
clientDone.Set();
});
clientDone.Reset();
socket.ConnectAsync(socketEventArg);
clientDone.WaitOne(TIMEOUT_MILLISECONDS);
return result;
}
public void SendToServer(string message)
{
SocketAsyncEventArgs asyncEvent = new SocketAsyncEventArgs { RemoteEndPoint = hostEntry};
Byte[] buffer = Encoding.UTF8.GetBytes(message + Environment.NewLine);
asyncEvent.SetBuffer(buffer, 0, buffer.Length);
socket.SendAsync(asyncEvent);
}
}
}
In my main client class, I have: client.SendToServer("hello!");
When I run the server and run the client the server detects the client but receives "104" instead of "Hello". Could anybody explain why this is happening and maybe provide a solution to the problem?
When you're doing clientStreamReader.Read() you're just reading one char as int from the stream. Check the doc here.
That's why you get only a number.
You need a delimeter to each message to know where it ends, \r\n is often used.
Here a sample to make your server receive your hello! String :
In your client Code
client.SendToServer("hello!" + "\r\n");
In your server Code
Console.WriteLine(clientStreamReader.ReadLine()); // Which should print hello!