yoga1290

yoga1290 / Dots game http server

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