yoga1290

C# project!

Feb 5th, 2011
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.90 KB | None | 0 0
  1. // Youssef Gamil [email protected]
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Threading;
  9. // http://shortText.com/97maimjr45j
  10. //HTTP server edited from http://www.123aspx.com/PostReview.aspx?res=75
  11. namespace dots_server
  12. {
  13. class HttpProcessor {
  14.         private games gm;
  15. private Socket s;
  16. private BufferedStream bs;
  17. private StreamReader sr;
  18. private StreamWriter sw;
  19. private String method; // ?
  20. private String url;
  21. private String protocol; // ?
  22. private Hashtable hashTable;
  23.  
  24. public HttpProcessor(Socket s,games g) {
  25. this.s = s;
  26.             this.gm=g;
  27. hashTable = new Hashtable();
  28. }
  29.  
  30. public void process() {
  31. NetworkStream ns = new NetworkStream(s, FileAccess.ReadWrite);
  32. bs = new BufferedStream(ns);
  33. sr = new StreamReader(bs);
  34. sw = new StreamWriter(bs);
  35.     parseRequest();
  36.     readHeaders();
  37.     writeURL();
  38.     s.Shutdown(SocketShutdown.Both);
  39.     ns.Close();
  40. }
  41.  
  42. public void parseRequest() {
  43. String request = sr.ReadLine();
  44. string[] tokens = request.Split(new char[]{' '});
  45. method = tokens[0];
  46. url = tokens[1];
  47. protocol = tokens[2];
  48. }
  49.  
  50. public void readHeaders() {
  51. String line;
  52. while((line = sr.ReadLine()) != null && line != "") {
  53. string[] tokens = line.Split(new char[]{':'});
  54. String name = tokens[0];
  55. String valuee = "";//
  56. for(int i = 1; i < tokens.Length; i++) {
  57. valuee += tokens[i];//
  58. if(i < tokens.Length - 1) tokens[i] += ":";
  59. }
  60.         //      Console.WriteLine(">>"+name+">>"+valuee); // HTTPVIEW
  61. hashTable[name] = valuee;//
  62. }
  63. }
  64.  
  65. public void writeURL() {
  66. try {
  67.                 //URL PART :D :P ;)!! ANYTHING CAN BE DONE HERE YUPPY!!
  68.     //  FileStream fs = new FileStream(url.Substring(1), FileMode.Open, FileAccess.Read);
  69.                 //test :)!
  70.                 if(url.Substring(1).Equals("favicon.ico")) return;
  71.                 String res=gm.showgame(url.Substring(1),(string)hashTable["Host"]);
  72.                 byte[] bout=System.Text.Encoding.ASCII.GetBytes(res);
  73.                 byte[] bout2=System.Text.Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\n"+
  74.                  "Allow: GET\n"+
  75.                  "MIME-Version: 1.0\n"+
  76.                  "Server : HMJ Basic HTTP Server\n"+
  77.                  "Content-Type: "+"text/html" + "\n"+
  78.                  "Content-Length: "+ bout.Length +
  79.                  "\n\n"+res);
  80.                writeSuccess(bout2.Length);
  81.         BufferedStream bs2 = new BufferedStream(new MemoryStream(bout2));
  82.         byte[] bytes = new byte[4096];
  83.         int read;
  84.         while((read = bs2.Read(bytes, 0, bytes.Length)) != 0) {
  85.             bs.Write(bytes, 0, read);
  86.         }
  87.         bs2.Close();
  88.     } catch(FileNotFoundException) {
  89. writeFailure();
  90. sw.WriteLine("File not found: " + url);
  91. }
  92. sw.Flush();
  93. }
  94.  
  95. public void writeSuccess(int fileLength) {
  96.             ///*
  97.             //<<<<
  98.             sw.Write(
  99.                      "HTTP/1.0 200 OK\n"+
  100.                  "Allow: GET\n"+
  101.                  "MIME-Version: 1.0\n"+
  102.                  "Server : HMJ Basic HTTP Server\n"+
  103.                  "Content-Type: "+"text/html" + "\n"+
  104.                  "Content-Length: "+ fileLength +
  105.                  "\n\n" );
  106.              //    */
  107. //sw.WriteLine("HTTP/1.0 200 OK"); //>>>>>
  108. //sw.WriteLine("Connection: close"); //>>>>>
  109. //sw.WriteLine(); //>>>>
  110. }
  111.  
  112. public void writeFailure() {
  113. sw.WriteLine("HTTP/1.0 404 File not found");
  114. sw.WriteLine("Connection: close");
  115. sw.WriteLine();
  116. }
  117. }
  118.  
  119. public class HttpServer {
  120.  
  121. // ============================================================
  122. // Data
  123.  
  124. protected int port;
  125.  
  126. // ============================================================
  127. // Constructor
  128.  
  129. public HttpServer() : this(80) {
  130. }
  131.  
  132. public HttpServer(int port) {
  133. this.port = port;
  134. }
  135.  
  136. // ============================================================
  137. // Listener
  138.  
  139.         private games gm;
  140. public void listen() {
  141. //Socket listener = new Socket(0, SocketType.SockStream, ProtocolType.ProtTCP); //>>>>>>
  142.             //Socket listener = new Socket(0, SocketType.Stream, ProtocolType.Tcp);
  143.             gm=new games();
  144.         TcpListener listener =  new System.Net.Sockets.TcpListener(IPAddress.Parse("127.0.0.1"),1290); //<<<<
  145. //IPAddress ipaddress = new IPAddress("127.0.0.1"); //>>>>>>
  146. //IPEndPoint endpoint = new IPEndPoint(ipaddress, port); //>>>>>
  147. //listener.Bind(endpoint); //>>>>
  148. //listener.Blocking = true; //>>>>>
  149. //listener.Listen(-1); />>>>>>
  150.             listener.Start(); //<<<<<
  151. while(true) {
  152. //Socket s = listener.Accept(); //<<
  153.                 Socket s = listener.AcceptSocket();
  154. HttpProcessor processor = new HttpProcessor(s,gm);
  155. Thread thread = new Thread(new ThreadStart(processor.process));
  156. thread.Start();
  157. }
  158. }
  159.  
  160. // ============================================================
  161. // Main
  162.  
  163. public static int Main(String[] args) {
  164. HttpServer httpServer;
  165. if(args.GetLength(0) > 0) {
  166. //httpServer = new HttpServer(args[0].ToUInt16()); // >>>>>>>>
  167.                 httpServer = new HttpServer(1290); //<<<<<
  168. } else {
  169. httpServer = new HttpServer();
  170. }
  171. Thread thread = new Thread(new ThreadStart(httpServer.listen));
  172. thread.Start();
  173. return 0;
  174. }
  175. }
  176.    
  177.    
  178. }
  179.  
  180.  
  181.  
  182.  
  183.  
  184.  
  185.  
  186.  
  187. //
  188. class games
  189. {
  190.     Dictionary<string, int> map = new Dictionary<string, int>();
  191.     public int N=0,H=10,W=10;
  192.     public String[] games_nam=new String[1000];
  193.     public Hashtable p1=new Hashtable();//player1 hosts/IPs
  194.     public Hashtable p2=new Hashtable();//player2 hosts/IPs
  195.     public bool[] free=new bool[1000];
  196.     public int[,,] g=new int[1000,50,50];
  197.     public string[,,] cell_owner=new string[1000,50,50]; //cell owner ;P1 or P2 via IP
  198.     private int[] dC=new int[]{0,0,-1,1};
  199.     private int[] dR=new int[]{-1,1,0,0};
  200.             string just2test="UDLR";
  201.     private string[] lastPlay=new string[1000];
  202.     private bool playAgain=false;
  203.         private int floodFill_game_ind;
  204.     private bool[,] vis=new bool[50,50];
  205.     private bool pass=true;
  206.     private string floodFill_owner;
  207.     private StreamWriter sw=new StreamWriter("log.txt");
  208.     /*
  209.            V= 0001 = up=1<<0
  210.           _________________
  211. 1<<2=left|<0100           |
  212.          |           >1000| =right=1<<3
  213.          |________________|
  214.                ^ 0010=down=1<<1
  215.      */
  216.     public games()
  217.     {
  218.         playAgain=false;
  219.         int i,j,k;
  220.         for(i=0;i<1000;i++)
  221.         {
  222.             free[i]=true;
  223.             lastPlay[i]="";
  224.                 for(j=0;j<H;j++)
  225.                     for(k=0;k<W;k++)
  226.                     {
  227.                         g[i,j,k]=0;
  228.                         cell_owner[i,j,k]="";
  229.                     }
  230.         }
  231.     }
  232.    
  233.     public string homee()
  234.     {
  235.         string txt="<html><head><title>Available Games:</title></head><body><p aligen='center'>Available Games:<br><table align='center'>";
  236.         for(int i=0;i<N;i++)
  237.             if(free[i])
  238.                 txt+="<tr><td align='center'><a href='/"+games_nam[i]+"'><font size=40>"+games_nam[i]+"</font></a></td></tr>";
  239.         txt+="</table>"+"<br><a href='javascript:location.href=prompt(\"Game Name:\");'>New Game!</a><br></p>"+"</body></html>";
  240.         return txt;
  241.     }
  242.  
  243.     public string showgame(string nam,string host)
  244.     {
  245.         if(nam=="") return homee();
  246.         if( nam.IndexOf('?')>-1)
  247.             if(
  248.             map.ContainsKey( nam.Substring(0,nam.IndexOf('?')) )
  249.           )
  250.             return play(
  251.                         nam.Substring(0,nam.IndexOf('?'))
  252.                         ,host
  253.                         , int.Parse(nam.Substring(nam.IndexOf('?')+1,nam.IndexOf(',')-nam.IndexOf('?')-1 ) )
  254.                         ,int.Parse(nam.Substring(nam.IndexOf(',')+1,nam.LastIndexOf(',')-nam.IndexOf(',')-1 ))
  255.                         ,int.Parse(nam.Substring(nam.LastIndexOf(',')+1)));
  256.        
  257.         string res="";
  258.         int i,j;
  259.         if(!map.ContainsKey(nam)) //New Game ya3ny & this is player1 :)
  260.         {
  261.             if(nam.IndexOf('?')>-1) return "<html><head><title>'?'!</title></head><body><script>alert('Game name can't include \"?\"! :-(');</script></body></html>";
  262.             if(N+1>=1000) return "<html><head><title>'?'!</title></head><body><script>alert('sorry,memory limit! :-(');</body></script></html>";
  263.             map.Add(nam,N);
  264.             free[N]=true;
  265.             games_nam[N++]=nam;
  266.             if(!p1.ContainsKey(host))
  267.             {
  268.                 sw.WriteLine("New Player1:\t"+host+"@"+nam+"\t"+new DateTime().ToShortTimeString());
  269.                 Console.WriteLine("New Player1:\t"+host+"@"+nam+"\t"+new DateTime().ToShortTimeString());
  270.                 p1.Add(host,true);
  271.             }
  272.         }
  273.         else //2nd player & the game is full!
  274.         {
  275.             if(!p1.ContainsKey(host) && !p2.ContainsKey(host))
  276.             {
  277. //              Console.WriteLine(">>>>>>>PLAYER 2<<<<<<<<<<=>"+host);
  278.                 free[map[nam]]=false;
  279.                 sw.WriteLine("New Player2:\t"+host+"@"+nam+"\t"+new DateTime().ToShortTimeString());
  280.                 Console.WriteLine("New Player2:\t"+host+"@"+nam+"\t"+new DateTime().ToShortTimeString());
  281.                 p2.Add(host,true);
  282.             }
  283.         }
  284.        
  285.     //  if(p1.ContainsKey(host)) color="Blue";
  286. //      else color="red";
  287.         /*
  288.            V= 0001 = up=1<<0
  289.           _________________
  290. 1<<2=left|<0100           |
  291.          |           >1000| =right=1<<3
  292.          |________________|
  293.                ^ 0010=down=1<<1
  294.      */
  295.         int ind=map[nam],r1=0,r2=0;
  296.         string color="";
  297.         res="<html><head><title>"+games_nam[ind]+"</title></head><body><table>";
  298.         for(i=0;i<H;i++)
  299.         {
  300.             res+="<tr>";
  301.             for(j=0;j<W;j++)
  302.             {
  303.                 if(p1.ContainsKey(cell_owner[ind,i,j]) && cell_owner[ind,i,j].Equals(cell_owner[ind,i,j]))
  304.                     {color="blue";r1++;}
  305.                 else if(p2.ContainsKey(cell_owner[ind,i,j]) && cell_owner[ind,i,j].Equals(cell_owner[ind,i,j]))
  306.                     {color="red";r2++;}
  307.                 else color="white";
  308.                
  309.                 res+="<td><table>";
  310.                 if( (g[ind,i,j]&(1<<0)) >0  ) //up
  311.                     res+="<tr><td bgcolor='"+color+"' width='70%'>====</td><td bgcolor='"+color+"' width='30%'>O</td></tr>";
  312.                 else
  313.                     res+="<tr><td bgcolor='"+color+"' width='70%'><a href='/"+games_nam[map[nam]]+"?"+i+","+j+","+(1<<0)+"'>====</a></td><td bgcolor='"+color+"' width='30%'>0</td></tr>";
  314.                
  315.                 if( (g[map[nam],i,j]&(1<<3)) >0  ) //right
  316.                     res+="<tr><td bgcolor='"+color+"' width='70%'></td><td bgcolor='"+color+"' width='30%'>||</td></tr>";
  317.                 else
  318.                     res+="<tr><td bgcolor='"+color+"' width='70%'></td><td bgcolor='"+color+"' width='30%'><a href='/"+games_nam[map[nam]]+"?"+i+","+j+","+(1<<3)+"'>||</a></td></tr>";
  319.                 res+="</table></td>";
  320.             }
  321.             res+="</tr>";
  322.         }
  323.         res+="</table><p aligen='center'>P1:"+r1+"<br>P2:"+r2+"</p><script>setTimeout('location.href=\""+games_nam[ind]+"\"; ',5000);</script></body></html>";
  324.        
  325.         return res;
  326.     }
  327.         /*
  328.            V= 0001 = up=1<<0
  329.           _________________
  330. 1<<2=left|<0100           |
  331.          |           >1000| =right=1<<3
  332.          |________________|
  333.                ^ 0010=down=1<<1
  334.      */
  335.    
  336.     public string play(string nam,string host,int x,int y,int v)
  337.     {
  338.         if(!map.ContainsKey(nam)) //set a new game?!
  339.             return homee();
  340. //check this host was last player or not!..HERE<
  341.         floodFill_game_ind=map[nam];
  342.         if(lastPlay[floodFill_game_ind].Equals(host) && (!playAgain))
  343.             return "<html><head><title>re-directing...</title></head><body><script>alert('Plz w8 4 other Player!');location.href='/"+nam+"';</script></body></html>";
  344.         if(playAgain) playAgain=false;
  345.         sw.WriteLine("\tPLAY \t"+host+"\t"+x+","+y+","+(v==8 ? "L":"U") );
  346.         Console.WriteLine("\tPLAY \t"+host+"\t"+x+","+y+","+(v==8 ? "L":"U") );
  347.         //handle other near cells opening
  348.         g[floodFill_game_ind,x,y] |=v;
  349.        
  350.         if( (v&(1<<0))>0 && x-1>=0) //up
  351.             g[floodFill_game_ind,x-1,y] |=(1<<1); //upper side is closed
  352.        
  353.         if( (v&(1<<2))>0 && y-1>=0) //left
  354.             g[floodFill_game_ind,x,y-1] |=(1<<3); //leftside is closed
  355.        
  356.         if( (v&(1<<3))>0 && y+1<W) //right
  357.             g[floodFill_game_ind,x,y+1] |=(1<<2); //rightside is closed
  358.        
  359.        
  360.         if( (v&(1<<1))>0 && x+1<H) //down
  361.             g[floodFill_game_ind,x+1,y] |=(1<<0); //bottom is closed
  362.        
  363.        
  364.  /*
  365.          for(int i=0;i<5;i++)
  366.         {
  367.             for(int j=0;j<5;j++)
  368.             {
  369.                 for(int k=0;k<4;k++)
  370.                     if( (g[floodFill_game_ind,i,j]&(1<<k)) >0)
  371.                         Console.Write(just2test[k]+"");
  372.                     else
  373.                         Console.Write("_");
  374.                 Console.Write("\t");
  375.             }
  376.             Console.WriteLine();
  377.         }      
  378. // */      
  379.         floodFill_game_ind=map[nam];
  380.         floodFill_owner=host;
  381.         vis=new bool[50,50];
  382.         Console.WriteLine("START FF :)...");
  383.         pass=true;
  384.         floodFill(x,y);
  385.         // IFF it doesn't exceed the boundaries,then this region exists :)
  386.         if(pass)
  387.         {
  388.                 playAgain=true;
  389.                 //Make him play 1 more time...HERE<
  390.                 vis=new bool[50,50];
  391.                 set_owner(x,y);
  392.                 Console.WriteLine("NEW REGION...The Happy END :)!");
  393.         }
  394.        
  395.         for(int i=0;i<4;i++)
  396.         {
  397.             vis=new bool[50,50];
  398.             this.pass=true;
  399.             floodFill(x+dR[i],y+dC[i]);
  400.             // IFF it doesn't exceed the boundaries,then this new region exists :)
  401.             if(pass)
  402.             {
  403.                     playAgain=true;
  404.                     //Make him play 1 more time...HERE<
  405.                     vis=new bool[50,50];
  406.                     set_owner(x+dR[i],y+dC[i]);
  407.                     Console.WriteLine("NEW REGION...The Happy END :)!");
  408.             }
  409.         }
  410.         lastPlay[floodFill_game_ind]=host;
  411.         return showgame(nam,host);
  412.     }
  413.     /*
  414.     private bool FFset(int x,int y)
  415.     {
  416.         if(x<0 || y<0 || x>=H || y>=W)
  417.             return false;
  418.         if(vis[x,y]) return true;
  419.         vis[x,y]=true;
  420.         cell_owner[floodFill_game_ind,x,y]=floodFill_owner;
  421.         for(int i=0;i<4;i++)
  422.             if( (g[floodFill_game_ind,x,y]&(1<<i)) ==0)
  423.                 if(!FFset(x+dR[i],y+dC[i]))
  424.                 {
  425.                     cell_owner[floodFill_game_ind,x,y]="";
  426.                     return false;
  427.                 }
  428.         return true;
  429.     }
  430.     */
  431.     private void floodFill(int x,int y)
  432.     {
  433.         if(x<0 || y<0 || x>=H || y>=W)
  434.         {
  435.             pass=false;
  436.             return;
  437.         }
  438.         if(vis[x,y]) return;
  439.         vis[x,y]=true;
  440.         for(int i=0;i<4;i++)
  441.             if( (g[floodFill_game_ind,x,y]&(1<<i)) ==0)
  442.                 floodFill(x+dR[i],y+dC[i]);
  443.     }
  444.    
  445.     private void set_owner(int x,int y)
  446.     {
  447.         //useless condition :P!;it wouldn't be a region iff it floods to the outer boundries!
  448.         if(x<0 || y<0 || x>=H || y>=W)  return;
  449.         if(vis[x,y]) return;
  450.         vis[x,y]=true;
  451.         if(!cell_owner[floodFill_game_ind,x,y].Equals("")) return;
  452.         cell_owner[floodFill_game_ind,x,y]=floodFill_owner;
  453.         for(int i=0;i<4;i++)
  454.             if( (g[floodFill_game_ind,x,y]&(1<<i)) ==0) //Avoid walls
  455.                 set_owner(x+dR[i],y+dC[i]);
  456.     }
  457. }
Add Comment
Please, Sign In to add comment