C# TcpListener Example

13 02 2008

Ok, this is just a quick snippet of code I wrote to get a working server up. Obviously theres more commands I could put in there in plenty of different ways, but I really just wanted to keep things simple for now. This took me about 2 hours.

This snippet is the main body of code that controls everything. If you go through it and read you’ll see that I made a struct to hold the information on files named File, in the namespace Structure. So you would access it by saying in this [MainNamespace].Structure.File; or you can just use Structure.File. I’ll paste the code for the struct at the end.

I didn’t leave too many comments because I used a lot of Writelines to tell me what it was doing, and for debugging purposes. Those kind of tell you what things do what.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace FizzSrvLight
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(“FizzSrvLight :: Non-Distributed Fizzure Serving Capabilities”);
System.Threading.Thread.Sleep(1000);
Console.Write(“Loading…”);
Console.WriteLine(“!”);

Console.WriteLine(“Initiating Server Variables…”);
System.Net.IPAddress localaddr = System.Net.IPAddress.Parse(“127.0.0.1″);

Console.WriteLine(“Constructing Server Objects…”);
System.Net.Sockets.TcpListener MainServer = new System.Net.Sockets.TcpListener(localaddr, 9000);

Console.WriteLine(“Starting Server…”);
MainServer.Start();

Byte[] bytes = new Byte[1024];
String data = null;
String send = null;

while (true)
{
Console.WriteLine(“Waiting for connection…”);

// Accept Requests
System.Net.Sockets.TcpClient client = MainServer.AcceptTcpClient();
Console.WriteLine(“Client Connected!”);

// Clear Buffers
data = null;
send = null;

// Get Stream Object for reading and writing
System.Net.Sockets.NetworkStream stream = client.GetStream();

int i;

// Initialize File Holder
System.Collections.ArrayList CurrentFiles = new System.Collections.ArrayList();

// Loop to recieve all data sent from client
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Clear buffers again
data = null;
send = null;
string message = “OK”;
// Get data as string
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine(“FIZZ_RCV: {0}”, data);

String[] command = data.Split(‘ ‘);

// Insert Possible Commands Here
if (command[0] == “FIZZ_ADDFILE”)
{
FizzSrvLight.Structure.File file = new FizzSrvLight.Structure.File(command[1], command[2], command[3], command[4], command[5], command[6]);
CurrentFiles.Add(file);
}
else if (command[0] == “FIZZ_RMVFILE”)
{
FizzSrvLight.Structure.File file = new FizzSrvLight.Structure.File(command[1], command[2], command[3], command[4], command[5], command[6]);
CurrentFiles.Remove(file);
}
else if (command[0] == “FIZZ_AUTH”)
{
string username = command[1];
string password = command[2];
}
else
{
Console.WriteLine(“FIZZ_INVALID_INPUT”);
Console.WriteLine(“Error Handled”);
message = “ERROR”;
}

send = message;

byte[] msg = System.Text.Encoding.ASCII.GetBytes(send);

// Send back an OK response;
stream.Write(msg, 0, msg.Length);
Console.WriteLine(“FIZZ_SND: ” + message);
}
System.Threading.Thread.Sleep(1000);
}
}
}
}

Now, time for the struct.

namespace FizzSrvLight
{
namespace Structure
{
public struct File
{
public string FileName;
public string FilePath;
public string FileType;
public string SharedBy;
public string IPAddress;
public string Blacklist;

public File(string name, string path, string type, string user, string ipaddr, string blacklisted)
{
FileName = name;
FilePath = path;
FileType = type;
SharedBy = user;
IPAddress = ipaddr;
Blacklist = blacklisted;
}

}
}
}

Well, there you have it. A very simple TcpListener Serve. Obviously theres better ways to do it but this is pretty simple, straight forward, and just all around easy. Please leave comments if you find bugs in it or see errors or even if you just don’t understand what some of it does.





The Team Grows

26 01 2008

As of yesterday, another programmer has joined the Fizzure project. This makes me very happy but at the same time, a little worried.

I am very happy about having another programmer to help me on this project for a bunch of reasons. It gives me someone to help me out when I am stuck on a bug. Someone to bounce my ideas off of and see what they think. Someone to do another portion of the programming. It is a huge help in a lot of ways.

However, at the same time, I am a little worried. I’ve never really worked with someone in a team on a large project before. I have to figure out the best way to keep code and things organized well between both people.

I am thinking of using Mercurial to help manage the code.  Luckily, the project is easily split into 2 quite separate parts – the Server and the Client. I will be working on the server, and the other programmer will be working on the client. Both of us wanted to almost start over from a code perspective because what I had written was pretty messy. I think it was quite a good idea. I’ve looked at his basic re-design of the client, and it looks pretty good. We are hoping to implement a skinning system for the client so people can make the program look according to their own likes.

I was not happy with the way the server was organized before so I decided to completely redo the structure. The server is going to be a distributed system so that it will be handled by several computers instead of just overloading one. I’m trying to make it an easily scalable and efficient distributed system. We’ll see how it turns out.

I haven’t spent too much time working with the new addition to the team, but the time we have spent has been great. We discuss the best way to do the current thing that we are working on instead of just going right to the first idea that pops into our heads. This, in the end, I think will cause a much more efficient and well organized program. We’ll see how everything turns out.





w00t – Great Success

9 01 2008

I know for most professional programmers and really anyone else in general it isn’t much of an accomplishment, but for me this is – I got the basic TCP connection working between the Fizzure client and server.

The server is just a lightweight console application. So far all it really does is accept connections. But for now I guess thats good enough. Today, I need to work on the XML usage of both the client and the server, and then the interaction with XML between the two. For efficiency I think I will do a lot of caching data. But I guess I need to figure out how to do that as well. I’m going to have to do a little more planning and deciding before I do too much programming.

Also though, I need to work on the GUI for the client.  I’m thinking about making it kind of skinnable. Or at least it will have different like color themes you can choose from. But eventually, I want it to be skinnable. People do seem to like that, it makes you feel like your program is just that much more personalizable.





Fizzure Will Go Open Source – When It’s Ready That Is

7 01 2008

I have decided that my peer to peer application, Fizzure, will be open source! Exciting, I know.

However, I don’t think that I will open the source until I have a working beta build. Right now its still in core development. And it has a long way to go. Only the client will be open source. The central server that all will keep the information organized will be private and closed source. Sorry fellas. Out of luck on that one.

Fizzure will be the first application that I will publish officially, so I’m not completely sure how to go about doing so. My friend suggested that since I’m opening the source I should put it under the GPL. Sounds like a good idea, but, how do I do this? If anyone has suggestions for a n00b like me on how to go about doing such that would be great. If not, I’m going to ask again later anyways, once it is closer to an actual release.





Great News For me – Less Work!

7 01 2008

Despite last nights extreme anger over the fact that I thought I was going to redo the structure of my Fizzure application, I learned today that I most likely do not! And this simple fact makes me very happy. There is almost nothing I hate more than having to redo work.

I came into school this morning with some of my code in hand and went straight to my computer science room. My teacher (the ever brilliant Dianne Meskauskas) took a quick look at my code. As it turns out I had just made a small mistake of where I had placed the creation of one of my objects.

The error I kept getting was a NullObjectException when I tried to access an array. I had made the creation of the object inside of a timer, so each time the timer ticked, it was creating a new object. On the first time it ticks, it creates the object “o” of the OptionControl class and fills the array SharedDirectories. On the second tick, it recreates “o” and tries to access the now empty array SharedDirectories, thus giving me the NullObjectException

Here is the little code snippet :

private void timer1_Tick(object sender, EventArgs e) {
OptionControl o = new OptionControl();
if (count == 0) {
loadWhat.Text = "Finding Shared Directories...";
o.SharedDirectories = o.getSharedDirs();
} else if (count == 1) {
loadWhat.Text = "Scanning Directories...";
o.DoScan();
} else if (count == 2) {
loadWhat.Text = "Shared Directories Found!";
} else {
Dispose(false);
}
count += 1;
}

My mistake here is on the first line. This line needs to be taken out of there and made as a class variable instead of inside a method, that way it can be accessed from any of the methods and have the same data as well.





This Is What Happens When You Don’t Plan Your Projects!

6 01 2008

Man, I am going to be completely honest with you.

I am very angry right now.

With my new project, Fizzure, I did what I always seem to do. I jumped into it. I got the idea a while ago and spent a week or so organizing some of my thoughts in my head. But that is the only place I organized them, and that was my mistake.

Once again, I got screwed over by not writing things down. I was up until about 4 A.M. last night working on this project (just because I could be) and I got stuck on an error. Which at 4 A.M, Isn’t all that unusual. But even today I couldn’t figure it out. Of course after wasting most of today on this error as well, I realized it was because almost my entire project was structured wrong and would not ever work if I continued programming the way I was.

So just like what normally happens. I have to delete a large amount of work, and almost start over. I’m sure you would be angry too! But, alas, I have no one to blame but myself. It is because I was too stubborn and lazy to write things down! But on the upside, it gives me something to do during my boring classes tomorrow. *laughs maniacally*

So a lesson I learned today about programming was to always write out some organizational thoughts about your project on paper before you start actually programming.

On the upside of things, I did figure out some useful things last night while I was working, like how to read and write XML as well as a small amount of file and directory handling – among other things. I believe I really just need to copy and paste a large amount of my code into different places. We’ll see.