I'm new in C# and I am practicing with Socket programming.
First I created a server for client connect to it.
Server:
class Program {
static void Main(string[] args) {
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 1900);
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
newsock.Bind(ipep);
Console.WriteLine("Waiting for a client...");
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)(sender);
recv = newsock.ReceiveFrom(data, ref Remote);
Console.WriteLine("Message received from {0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
string welcome = "Welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
while (true) {
data = new byte[1024];
recv = newsock.ReceiveFrom(data, ref Remote);
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
newsock.SendTo(data, recv, SocketFlags.None, Remote);
}
}
}
Client:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace serverUDPWF {
public partial class ServerForm : Form {
byte[] data = new byte[30];
string input = "";
string stringData = "";
IPEndPoint iep,sender;
Socket server;
string welcome = "";
int recv;
EndPoint tmpRemote;
public ServerForm() {
InitializeComponent();
startServer();
}
public void startServer() {
iep = new IPEndPoint(
IPAddress.Parse("127.0.0.1"), 1900);
server = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
welcome = "Hello, are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, iep);
sender = new IPEndPoint(IPAddress.Any, 0);
tmpRemote = (EndPoint)sender;
data = new byte[30];
recv = server.ReceiveFrom(data, ref tmpRemote);
Console.WriteLine();
listBox1.Items.Add("Message received from {0}:" + tmpRemote.ToString());
listBox1.Items.Add(Encoding.ASCII.GetString(data, 0, recv));
}
private void sendMessageToserver(object sender, EventArgs e) {
if (textBox2.Text == "") {
MessageBox.Show("Please Enter Your Name");
}
else {
int i = 30;
input = textBox2.Text + ": " + textBox1.Text;
if (input == "exit") {
this.Close();
}
server.SendTo(Encoding.ASCII.GetBytes(input), tmpRemote);
textBox1.Text = "";
data = new byte[i];
try {
recv = server.ReceiveFrom(data, ref tmpRemote);
stringData = Encoding.ASCII.GetString(data, 0, recv);
listBox1.Items.Add(stringData);
}
catch (SocketException) {
listBox1.Items.Add("WARNING: data lost, retry message.");
i += 10;
}
}
}
}
}
My problem is how to make client not need to enter the server ip address like 127.0.0.1. My Second problem is I open 2 client in the same time, but client A sends a message to server but client B doesn't receive a message from client A (I want send a broadcast type message)
How can I do that?
Multicast udp communication.. i just try if anything wrong feel free to share
Client:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Threading;
namespace Myclient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
Socketsending socketsending;
string multicastIP = string.Empty;
int multicastPort = 0;
int clientPort = 0;
string clientSysname = string.Empty;
string Nodeid = string.Empty;
string clientIP = string.Empty;
string recievedText = string.Empty;
string sendingText = string.Empty;
IPAddress ipAddress;
IPEndPoint ipEndpoint;
UdpClient udpClient;
string[] splitRecievedText;
byte[] byteRecieve;
private void Form1_Load(object sender, EventArgs e)
{
Random _random = new Random();
multicastIP = "224.5.6.7";
multicastPort = 5000;
Nodeid = "node" + _random.Next(1000, 9999);
clientPort = _random.Next(1000, 9999);
clientSysname = Dns.GetHostName();
ipAddress = Dns.GetHostEntry(clientSysname).AddressList.FirstOrDefault
(addr => addr.AddressFamily.Equals(AddressFamily.InterNetwork));
ipEndpoint = new IPEndPoint(ipAddress, clientPort);
clientIP = ipAddress.ToString();
label1.Text = "Node id: " + Nodeid;
label2.Text = "Host Name: " + clientSysname;
Thread threadMain = new Thread(connect);
threadMain.Start();
threadMain = new Thread(receive);
threadMain.Start();
}
void connect()
{
socketsending = new Socketsending();
sendingText = "connect#" + clientSysname + "#" + clientIP + "#" + clientPort + "#" + Nodeid + "#";
socketsending.send(multicastIP, multicastPort, sendingText);
}
void receive()
{
udpClient = new UdpClient(clientPort);
while (true)
{
IPEndPoint _ipendpoint = null;
byteRecieve = udpClient.Receive(ref _ipendpoint);
recievedText = Encoding.ASCII.GetString(byteRecieve);
splitRecievedText = recievedText.Split('#');
if (splitRecievedText[0] == "stop")
{
}
}
}
private void button1_Click(object sender, EventArgs e)
{
sendingText = "message#" + Nodeid + '$' + textBox1.Text + '$';
socketsending.send(multicastIP, multicastPort, sendingText);
}
}
}
Server:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Collections;
namespace Myserver
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
string multicastip = string.Empty;
string serversystemname = string.Empty;
string receiveddata = string.Empty;
string nodeinfo = string.Empty;
string clientHostName = string.Empty;
string clientIP = string.Empty;
string Nodeid = string.Empty;
int multicastport = 0;
int clientport = 0;
DataTable datatable;
DataTable dataTableAddRemove;
string[] splitReceived;
string[] splitnodeinfo;
Socket socket;
IPAddress ipaddress;
IPEndPoint ipendpoint;
byte[] bytereceive;
Dictionary<string, string> dictionarytable;
public delegate void updategrid();
private void Form1_Load(object sender, EventArgs e)
{
multicastip = "224.5.6.7";
multicastport = 5000;
serversystemname = Dns.GetHostName();
datatable = new DataTable();
datatable.Columns.Add("HostName");
datatable.Columns.Add("Nodeid");
datatable.Columns.Add("ipaddress");
datatable.Columns.Add("portnumber");
DGV.DataSource = datatable;
Thread threadreceive = new Thread(receiver);
threadreceive.Start();
}
void receiver()
{
dictionarytable = new Dictionary<string, string>();
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
ipendpoint = new IPEndPoint(IPAddress.Any, multicastport);
socket.Bind(ipendpoint);
ipaddress = IPAddress.Parse(multicastip);
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ipaddress, IPAddress.Any));
while (true)
{
bytereceive = new byte[4200];
socket.Receive(bytereceive);
receiveddata = Encoding.ASCII.GetString(bytereceive, 0, bytereceive.Length);
splitReceived = receiveddata.Split('#');
if (splitReceived[0].ToString() == "connect")
{
nodeinfo = splitReceived[1].ToString();
connect();
}
else if (splitReceived[0].ToString() == "Disconnect")
{
nodeinfo = splitReceived[1].ToString();
Thread threadDisconnect = new Thread(disconnect);
threadDisconnect.Start();
}
else if (splitReceived[0].ToString() == "message")
{
string[] str = splitReceived[1].Split('$');
listBox1.Items.Add(str[0] + " -> " + str[1]);
}
}
}
void connect()
{
SocketSending socketsending = new SocketSending();
int count = 0;
splitnodeinfo = nodeinfo.Split('#');
clientHostName = splitnodeinfo[0].ToString();
clientIP = splitnodeinfo[1].ToString();
clientport = Convert.ToInt32(splitnodeinfo[2].ToString());
Nodeid = splitnodeinfo[3].ToString();
if (!dictionarytable.ContainsKey(Nodeid))
{
count++;
dictionarytable.Add(Nodeid, clientIP + "#" + clientport + "#" + clientHostName);
dataTableAddRemove = (DataTable)DGV.DataSource;
DataRow dr = dataTableAddRemove.NewRow();
dr["Nodeid"] = Nodeid;
dr["HostName"] = clientHostName;
dr["IPAddress"] = clientIP;
dr["portNumber"] = clientport;
dataTableAddRemove.Rows.Add(dr);
datatable = dataTableAddRemove;
updatenodegrid();
}
}
void disconnect()
{
SocketSending socketsending = new SocketSending();
string removeClient = string.Empty;
splitnodeinfo = nodeinfo.Split('#');
clientHostName = splitnodeinfo[0].ToString();
Nodeid = splitnodeinfo[1].ToString();
dataTableAddRemove = (DataTable)DGV.DataSource;
DataRow[] arrayDataRow = dataTableAddRemove.Select();
for (int i = 0; i < arrayDataRow.Length; i++)
{
string matchGridHostName = arrayDataRow[i]["HostName"].ToString();
if (clientHostName == matchGridHostName)
{
Thread.Sleep(100);
removeClient = clientHostName;
arrayDataRow[i].Delete();
break;
}
}
if (dictionarytable.ContainsKey(removeClient))
{
dictionarytable.Remove(removeClient);
}
}
void updatenodegrid()
{
if (this.DGV.InvokeRequired)
this.DGV.Invoke(new updategrid(updatenodegrid));
else
DGV.DataSource = datatable;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
dictionarytable.Clear();
}
}
}
Related
I want to create a proxy server, but I'm having trouble communicating with ssl
I've tried a lot and failed sites that support http don't work it's just preparing the connection it works (google)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Threading;
using System.Diagnostics;
using System.Net.Sockets;
using System.IO;
using System.Net.Http.Headers;
using System.Runtime.Remoting.Messaging;
using RestSharp;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Data;
using System.Security.Policy;
using System.Security.Authentication;
using System.Runtime.ConstrainedExecution;
namespace Proxy
{
internal class Program
{
public static HttpListener listener;
static void Main(string[] args)
{
var ip = IPAddress.Parse("127.0.0.1");
Start(ip, 2020);
}
public static void Start(IPAddress ip, int port)
{
try
{
serverCertificate = X509Certificate.CreateFromCertFile("C:\\Users\\AK\\Desktop\\FiddlerRoot.cer");
TcpListener listener = new TcpListener(ip, port);
listener.Start(100);
while (true)
{
Socket client = listener.AcceptSocket();
IPEndPoint rep = (IPEndPoint)client.RemoteEndPoint;
Thread thread = new Thread(ThreadHandleClient);
thread.Start(client);
}
listener.Stop();
}
catch (Exception ex)
{
Console.WriteLine("START: " + ex.Message);
}
}
public static void ThreadHandleClient(object o)
{
try
{
Socket client = (Socket)o;
Console.WriteLine("===================================================================================");
Console.WriteLine("=========================Request=========================================");
Console.WriteLine("===================================================================================");
NetworkStream ns = new NetworkStream(client);
byte[] buffer = new byte[2048];
int rec = 0;
string data = "";
do
{
rec = ns.Read(buffer, 0, buffer.Length);
data += Encoding.ASCII.GetString(buffer, 0, rec);
} while (rec == buffer.Length);
Console.WriteLine(data);
Console.WriteLine("===================================================================================");
Console.WriteLine("=========================URL=========================================");
Console.WriteLine("===================================================================================");
string line = data.Replace("\r\n", "\n").Split(new string[] { "\n" }, StringSplitOptions.None)[0];
string UrlString = line.Split(new string[] { " " }, StringSplitOptions.None)[1];
var url = UrlString.EndsWith(":443") ? "https://" + UrlString.Replace(":443", "") : UrlString.Replace(":80", "");
Uri uri = new Uri(url);
Console.WriteLine(url);
Console.WriteLine("===================================================================================");
Console.WriteLine("=========================Response=========================================");
Console.WriteLine("===================================================================================");
if (uri.Scheme == "https")
{
Https(client, uri.Host, data);
}
else
{
Http(client, uri.Host, data);
}
}
catch (Exception ex)
{
Console.WriteLine("Error occured: " + ex.Message);
}
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate,X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
private static void Https( Socket clients,string Url,string datas)
{
TcpClient client = new TcpClient(Url, 443);
SslStream sw = new SslStream(client.GetStream());
sw.AuthenticateAsClient(Url);
string[] headers = datas.Split('\n');
foreach (string header in headers)
{
byte[] data = Encoding.UTF8.GetBytes(header + "\n\n");
sw.Write(data);
}
TcpClient el = new TcpClient();
el.Client = clients;
SslStream Send = new SslStream(el.GetStream(), true);
var cert = new X509Certificate2(sw.RemoteCertificate);
Send.AuthenticateAsServer(cert, true,true);
byte[] buffer = new byte[2048];
StringBuilder messageData = new StringBuilder();
int bytes = -1;
do
{
bytes = sw.Read(buffer, 0, buffer.Length);
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
Send.Write(buffer,0, bytes);
decoder.GetChars(buffer, 0, bytes, chars, 0);
messageData.Append(chars);
if (messageData.ToString().IndexOf("<EOF>") != -1)
{
break;
}
} while (bytes != 0);
client.Close();
Console.WriteLine(messageData.ToString());
Console.WriteLine("===================================================================================");
// This is where you read and send data
}
private static void Http(Socket clients, string Url, string datas)
{
IPHostEntry hostEntry;
hostEntry = Dns.GetHostEntry(Url);
EndPoint hostep = new IPEndPoint(hostEntry.AddressList[0], 80);
Socket sock = new Socket(hostEntry.AddressList[0].AddressFamily, SocketType.Stream, ProtocolType.Tcp);
datas = datas.Replace("http://"+Url, "");
sock.Connect(hostep);
string[] headers=datas.Split('\n');
foreach (string header in headers)
{
byte[] data = Encoding.UTF8.GetBytes(header+"\n\n");
sock.Send(data, 0, data.Length, SocketFlags.None);
}
byte[] bytes = new byte[2020];
int Rs = 0;
StringBuilder builder = new StringBuilder();
do
{
Rs=sock.Receive(bytes);
clients.Send(bytes, Rs, (SocketFlags)0);
builder.Append(Encoding.UTF8.GetString(bytes,0,Rs));
} while (Rs !=0);
Console.WriteLine(builder.ToString());
Console.WriteLine("===================================================================================");
}
}
public class Certificate
{
public static X509Certificate2 GetCertificate()
{
return new X509Certificate2(Properties.Resources.FiddlerRoot);
}
}
}
I've tried a lot and failed sites that support http don't work, it's just preparing the connection it works (google).
I am working on creating web application and i am getting problem redirecting to another page,if I use redirect code in another method then it works fine but i want to use redirect code from my running thread and it is throwing me HttpExeption.Please can you take a look at this code and show right way to use redirect code in my runloop() method.Thanks in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
using System.Threading.Tasks;
public partial class _Default : System.Web.UI.Page
{
static TcpListener listener;
static TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public String receive = "kkkk";
public String text_to_send;
string Jsn;
string URI ;
string myParameters;
string URL1;
Thread backgroundThread2;
Thread backgroundThread;
int i, n = 0, k = 0, len = 0, len2 = 0;
public int readflag = 0, writeflag = 0, pre1 = 0, pre2 = 0, pre3 = 0, nopre = 0;
char[] ch = new char[100];
char[] ch1 = new char[100];
char[] ch2 = new char[100];
String test = null, s1, s2, s3;
String test1 = null;
string frame;
const int LIMIT = 5; //5 concurrent clients
protected void Page_Load(object sender, EventArgs e)
{
frame = Request.QueryString["frame"];
if (Request.QueryString["Frame"] != null)
Response.Write("From Page1 param1 value=" + Request.QueryString["frame"]);
}
public void Button1_Click(object sender, EventArgs e) //start server
{
listener = new TcpListener(IPAddress.Any, 8002);
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
backgroundThread = new Thread(new ThreadStart(RunLoop));
backgroundThread.Start();
// Task.Delay(50000);
//redirect1();
// Response.Redirect(URL1);
}
public void Button2_Click(object sender, EventArgs e) //Redirect server
{
Jsn = "25";
string URI = "Otherpage.aspx?";
string myParameters = "jasonop="+ Jsn;
string URL1 = URI + myParameters;
Response.Redirect(URL1);
// Response.Redirect("Otherpage.aspx?jasonop=25");
// System.Diagnostics.Process.Start("http://localhost:85/shaktijason/1.php?jasonop=25");
}
public class Person
{
public string Name { get; set; }
}
public void RunLoop() //receive
{
NetworkStream stream = client.GetStream();
Byte[] bytes = new Byte[256];
String data = null;
int i,k=1;
string str = "";
JavaScriptSerializer js = new JavaScriptSerializer();
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
byte[] bHex = Encoding.ASCII.GetBytes(data);
// TextBox1.Text = data;
string json = "[{Name:'01030008000105C8'}]";
Person[] persons = js.Deserialize<Person[]>(json);
string name = persons[0].Name.ToString();
// STW.WriteLine("01030008000105C8")
STW.WriteLine(name);
string result = decodedata(data);
str = result;
k++;
if (k == 4) { break; }
}
// string returnJson = "[{Freq:'" + str + "'}]";
Jsn = GetDeviceJSON(str);
URI = "Otherpage.aspx?";
myParameters = "jasonop="+Jsn;
URL1 = URI + myParameters;
Response.Redirect(URL1,false);
// Response.Redirect("Otherpage.aspx");
//string URI = "http://localhost:85/Shaktijason/1.php";
//string myParameters = "jasonop=jsn";
//using (WebClient wc = new WebClient())
//{
// wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
// string HtmlResult = wc.UploadString(URI, myParameters);
// Response.Redirect(HtmlResult);
//}
//string JSON = Json;
//backgroundThread2.Start();
// backgroundThread.Abort();
//return js.Serialize(returnJson);
}
public string decodedata(string data)
{
ch1 = data.ToCharArray();
ch2 = data.ToCharArray();
int len1 = data.Count(char.IsLetter);
len2 = data.Count(char.IsNumber);
int add = len1 + len2;
while (ch1[k] != 'k')
{
ch2[k] = ch1[k];
k++;
}
string strng = new string(ch2, 0, k);
len = strng.Length;
string sub = data.Substring(k + 1);
len2 = sub.Length;
k = 0;
if (len == 1)
{
strng = "0" + strng.PadLeft(len, '0');
}
if (len2 == 1)
{
sub = "0" + sub.PadLeft(len2, '0');
}
char[] go = new char[20];
string final = strng + sub;
if (final.Equals("00b8"))
{
final = "0";
}
Decimal intAgain = long.Parse(final, System.Globalization.NumberStyles.HexNumber);
intAgain = intAgain / 100;
string final3 = intAgain.ToString();
// string final2 = new string(go);
return final3;
}
[WebMethod]
public static string GetValues(string values)
{
return values;
}
public string GetDeviceJSON(String str)
{
Device[] emps = new Device[] {
new Device()
{
Freq=str
}
//new employee()
//{
// id=102,
// name="dinesh",
// salary=100000
//}
};
return new JavaScriptSerializer().Serialize(emps);
}
}
You are trying to access the Reponse object from a background thread, where the response is already long gone.
You are not allowed to access the Response object, or any other object under HttpContext after the page has stopped rendering. Use web sockets or AJAX calls to create asynchronous requests and responses.
I am currently learning to program a chat room application that uses a server. So far everything works fine if I run the server and multiple instances of the application on a single machine. When I try to run the server on one machine and the actual chat application from another, I get an exception that reads "a connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond (Ipaddress)(port)"
Server side code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Collections;
using System.Text;
using System.Threading;
namespace ChatAppServer
{
class Program
{
public static Hashtable ClientList = new Hashtable();
const int PORT = 321;
string localIp;
static void Main(string[] args)
{
TcpListener sckServer = new TcpListener(PORT);
TcpClient sckClient = default(TcpClient);
int counter = 0;
sckServer.Start();
Console.WriteLine("Chat Server is now Running ....");
counter = 0;
//Parser myParser = new Parser();
while (true)
{
counter = counter + 1;
sckClient = sckServer.AcceptTcpClient();
string clientData = "";
byte[] recieveData = new byte[10025];
NetworkStream netStream = sckClient.GetStream();
netStream.Read(recieveData, 0, (int)sckClient.ReceiveBufferSize);
clientData = System.Text.Encoding.ASCII.GetString(recieveData);
clientData = clientData.Substring(0, clientData.IndexOf("$"));
ClientList.Add(clientData, sckClient);
Broadcast(clientData + " joined the chat", clientData, false);
Console.WriteLine(clientData + " connected to the chat");
handleClient client = new handleClient();
client.ClientStart(sckClient, clientData, ClientList);
}
sckClient.Close();
sckServer.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}
public static void Broadcast(string msg, string userName, bool flag)
{
foreach (DictionaryEntry Item in ClientList)
{
TcpClient sckBroadcast;
sckBroadcast = (TcpClient)Item.Value;
NetworkStream broadcastStream = sckBroadcast.GetStream();
Byte[] broadcastData = null;
if (flag == true)
{
broadcastData = Encoding.ASCII.GetBytes(userName + ": " + msg);
}
else
{
broadcastData = Encoding.ASCII.GetBytes(msg);
}
broadcastStream.Write(broadcastData, 0, broadcastData.Length);
broadcastStream.Flush();
}
}
public class handleClient
{
TcpClient sckClient;
string clId;
Hashtable ClientList;
public void ClientStart(TcpClient inSckClient, string clientId, Hashtable clist) {
this.sckClient = inSckClient;
this.clId = clientId;
this.ClientList = clist;
Thread ctThread = new Thread(runChat);
ctThread.Start();
}
private void runChat() {
int requestCount = 0;
byte[] recieveData = new byte[10025];
string clientData = "";
string rCount = null;
while ((true))
{
try
{
requestCount += 1;
NetworkStream netStream = sckClient.GetStream();
netStream.Read(recieveData, 0, (int)sckClient.ReceiveBufferSize);
clientData = System.Text.Encoding.ASCII.GetString(recieveData);
clientData = clientData.Substring(0, clientData.IndexOf("$"));
Console.WriteLine(clId + " : " + clientData);
rCount = Convert.ToString(requestCount);
Program.Broadcast(clientData, clId, true);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
}
}
Chat room application code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//Need for the application
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ChatApp
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient sckClient = new System.Net.Sockets.TcpClient();
NetworkStream svrStream = default(NetworkStream);
string recieveData = null;
public Form1()
{
InitializeComponent();
btnSend.Enabled = false;
}
private void btnConnect_Click(object sender, EventArgs e)
{
recieveData = "Connected to Server";
msg();
int serverPort = Convert.ToInt32(txtServerPort.Text);
sckClient.Connect(txtServerIp.Text, serverPort);
svrStream = sckClient.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtUserName.Text + "$");
svrStream.Write(outStream, 0, outStream.Length);
svrStream.Flush();
Thread ctThread = new Thread(MessageCallBack);
btnSend.Enabled = true;
btnConnect.Enabled = false;
txtUserName.Enabled = false;
txtServerIp.Enabled = false;
txtServerPort.Enabled = false;
ctThread.Start();
}
private void MessageCallBack()
{
while(true)
{
svrStream = sckClient.GetStream();
int buffSize = 0;
byte[] inStream = new byte[10025];
buffSize = sckClient.ReceiveBufferSize;
svrStream.Read(inStream, 0, buffSize);
string returnData = System.Text.Encoding.ASCII.GetString(inStream);
recieveData = "" + returnData;
msg();
}
}
//function to display data strings
private void msg()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(msg));
}
else
{
lstMessage.Items.Add(recieveData);
}
}
private void btnSend_Click(object sender, EventArgs e)
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtMessage.Text + "$");
svrStream.Write(outStream, 0, outStream.Length);
svrStream.Flush();
txtMessage.Text = "";
}
I have two troubles with your code :
Do not use .ReceiveBufferSize value because it's a different value of your byte array length. And you can have an index out of range exception.
You have a problem of concurrency in the server side. More than 1 thread try to access to the ClientList and this collection is not thread-safe.
To resolve this, you can use the lock keyword
private static object _lock = new object();
//...
lock (_lock)
{
ClientList.Add(clientData, sckClient);
}
lock (_lock)
{
Broadcast(clientData + " joined the chat", clientData, false);
}
//...
lock (_lock)
{
Program.Broadcast(clientData, clId, true);
}
As you're a beginner, i would give you some tips.
Try to use the asynchronous network functions (better than raw threads), an example there.
There is a lot of tutorials about safety with severals connections in C# (with some thing else, better, than the lock keyword).
I am trying to program an ident sever to deal with the identity protocol requests from an irc server that I am programming an irc client for. The problem is I try to print to the screen the what I receive but nothing prints. I am not getting an error code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace ConnectIRC
{
class IdentityClass
{
private const int bufSize = 32;
public void IdentityRequest() {
TcpListener listener = null;
int port = 113;
IPEndPoint hostInfo = new IPEndPoint(IPAddress.Any, 113);
listener = new TcpListener(hostInfo);
listener.Start();
byte[] rcvBuffer = new byte[bufSize];
int rec;
for (; ; )
{
TcpClient client = null;
NetworkStream netStream = null;
client = listener.AcceptTcpClient();
if (listener.Pending())
{
Console.WriteLine("Connection was made");
}
netStream = client.GetStream();
//byte[] rcvBuffer = new byte[bufSize];
rec = netStream.Read(rcvBuffer, 0, rcvBuffer.Length);
Array.Resize(ref rcvBuffer, rec);
Console.WriteLine(Encoding.ASCII.GetString(rcvBuffer));
netStream.Close();
client.Close();
}
}
}
}
This is a very basic implementation of an ident server
Obviously it only accepts one connection and closes
Note you'll need to have a port mapped through your router for this to work
public class Ident
{
private readonly TcpListener _listener;
private readonly string _userId;
public Ident(string userId)
{
_userId = userId;
_listener = new TcpListener(IPAddress.Any, 113);
}
public void Start()
{
Console.WriteLine("Ident started");
_listener.Start();
var client = _listener.AcceptTcpClient();
_listener.Stop();
Console.WriteLine("Ident got a connection");
using (var s = client.GetStream())
{
var reader = new StreamReader(s);
var str = reader.ReadLine();
var writer = new StreamWriter(s);
Console.WriteLine("Ident got: " + str + ", sending reply");
writer.WriteLine(str + " : USERID : UNIX : " + _userId);
writer.Flush();
Console.WriteLine("Ident sent reply");
}
Console.WriteLine("Ident server exiting");
}
}
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
tcp/ip client server not working over internet
i spent the last week working on a simple windows form application that' s supposed to send a couple of integer numbers from client to server or from server to client. So far i have only managed to make it work for lanns, any idea about how to make it work on the open internet ?
Here' s the code in case you need it (also call me noob but i can' t get how this site handles code, ... does not do what i thought it did so feel free to edit my post in case i fail2format)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace client_server_penta
{
public class Client
{
#region Fields
private int turno = 1;
private TcpClient[] clients = new TcpClient[1]; //used to remember the active client
private int CoordinateX, CoordinateY; //coordinates, they are used by the application
#endregion
public Client(string address)
{
TcpClient client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(address), 3000);
client.Connect(serverEndPoint);
clients[0] = client;
Thread ReadFromServer = new Thread(new ParameterizedThreadStart(this.ReadHandler));
ReadFromServer.Start(client);
}
public void SendData(int a, int b)
{
NetworkStream clientStream = clients[0].GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(a.ToString() + '$' + b.ToString() + '$');
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
public int ReadCoordinateX()
{
return this.CoordinateX;
}
public int ReadCoordinateY()
{
return this.CoordinateY;
}
private void ReadHandler(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] buffer;
int bytesRead;
while (true)
{
buffer = new byte[10];
bytesRead = 0;
try
{
bytesRead = clientStream.Read(buffer, 0, buffer.Length);
}
catch
{
//an uknown error has occurred
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//data received
ASCIIEncoding encoder = new ASCIIEncoding();
OnDataReceived(encoder.GetString(buffer, 0, buffer.Length));
}
tcpClient.Close();
}
private void OnDataReceived(string text)
{
string first_number = "";
string second_number = "";
int index = 0;
while (text[index] != '$')
first_number += text[index++];
index++;
while (text[index] != '$')
second_number += text[index++];
this.CoordinateX = Convert.ToInt32(first_number);
this.CoordinateY = Convert.ToInt32(second_number);
var myForm = Application.OpenForms["Form2"] as Form2;
myForm.Text = "Turno N." + Convert.ToString(this.turno++);
}
}
}
//and here' s the server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace client_server_penta
{
public class Server
{
private Thread listenThread;
private int turno = 1;
private TcpListener tcpListener;
private TcpClient[] clients = new TcpClient[1]; //used to remember the active client
private int CoordinateX, CoordinateY; //coordinates, they are used by the application
public Server(int port)
{
this.tcpListener = new TcpListener(IPAddress.Any, 3000);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
public void SendData(int a, int b)
{
NetworkStream clientStream = clients[0].GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(a.ToString()+'$'+b.ToString()+'$');
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
public int ReadCoordinateX()
{
return this.CoordinateX;
}
public int ReadCoordinateY()
{
return this.CoordinateY;
}
private void ListenForClients()
{
this.tcpListener.Start();
TcpClient client = this.tcpListener.AcceptTcpClient();
clients[0] = client;
Thread ReadFromClient = new Thread(new ParameterizedThreadStart(this.ReadHandler));
ReadFromClient.Start(client);
}
private void ReadHandler(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] buffer = new byte[10];
int bytesRead;
while (true)
{
buffer = new byte[10];
bytesRead = 0;
try
{
bytesRead = clientStream.Read(buffer, 0, buffer.Length);
}
catch
{
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//data received
ASCIIEncoding encoder = new ASCIIEncoding();
OnDataReceived(encoder.GetString(buffer, 0, buffer.Length));
}
tcpClient.Close();
}
private void OnDataReceived(string text)
{
string first_number = "";
string second_number = "";
int index = 0;
while (text[index] != '$')
first_number += text[index++];
index++;
while (text[index] != '$')
second_number += text[index++];
this.CoordinateX = Convert.ToInt32(first_number);
this.CoordinateY = Convert.ToInt32(second_number);
var myForm = Application.OpenForms["Form2"] as Form2;
myForm.Text = "Turno N."+Convert.ToString(this.turno++);
}
}
}
Have you opened the 3000 port on your firewall on the two sides ?
Yes of course ^^
If you have routers, don't forget to edit the configurations too.