TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
lil iza lila
NA
4
0
Really need help on this (client-server programming using socket)
Oct 29 2009 10:28 PM
Hi experts out there....
I'm newbie here....and i really need ur help on below code. All i wanted to do is, i need to create simple chatting program which can server 2 client simultaneously. i try using array but doesn't work (because i do not know where to put the array correctly). here is my code (the server part). from my understanding is, only the server part will have an array to serve more than 1 socket created...correct me if i'm wrong.
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
class ServerSocket1
{
public static void Main()
{
try
{
bool status = true;
string serverMsg = "";
string clientMsg = "";
const int port = 8100;
const string IPadd = "127.0.0.1";
// create and bind socket
TcpListener serverSock = new TcpListener(IPAddress.Parse(IPadd), port);
//start listen to incoming connection
serverSock.Start();
Console.WriteLine("Server Started");
//serve two client
Socket[] clientSock = new Socket[2];
int client = 2;
for (int i = 0; i < client; i++)
{
//accept request from client
clientSock[i] = serverSock.AcceptSocket();
int clientNum = i + 1;
Console.WriteLine("Wating for client number {0} at host {1}and port {2}", clientNum,IPadd,port);
}
for (int i = 0; i < client; i++)
{
NetworkStream netStream = new NetworkStream(clientSock[i]);
//write message to client
StreamWriter streamwriter = new StreamWriter(netStream);
//read message from client
StreamReader streamreader = new StreamReader(netStream);
while (status)
{
if (clientSock[i].Connected)
{
serverMsg = streamreader.ReadLine();
Console.WriteLine("Client {0} :", clientSock[i] + serverMsg);
if ((serverMsg == "bye"))
{
status = false;
streamreader.Close();
streamwriter.Close();
networkStream[i].Close();
return;
}
Console.Write("Server:");
clientMsg = Console.ReadLine();
streamwriter.WriteLine(clientMsg);
streamwriter.Flush();
}
streamreader.Close();
networkStream[i].Close();
streamwriter.Close();
clientSock[i].Close();
Console.WriteLine("Exiting");
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
Reply
Answers (
2
)
dataGrid/datatype display
socket programming in windows moblle