Professional Documents
Culture Documents
To Solution
Bn to 1 solution c tn chng hn l SocketInCSharp. 1. u tin l server: Add 1project, t tn l SocketServer, thm 1 form v trn form thm 1 nt c tn Start. Kt qu nh sau:
01 using System; 02 using System.Collections.Generic; 03 using System.ComponentModel; 04 using System.Data; 05 using System.Drawing; 06 using System.Text; 07 using System.Windows.Forms; 08 using System.Net; 09 using System.Net.Sockets; 10 using System.Runtime.Serialization; 11 using System.Runtime.Serialization.Formatters.Binary; 12 using System.IO; 13 namespace SocketServer 14 { 15 public partial class Form1 : Form 16 { 17 private Socket sock = null; 18 public Form1() 19 { 20 InitializeComponent(); 21 } 22 23 private void startButton_Click(object sender, EventArgs e) 24 { 25 startButton.Text = "In process..."; 26 Application.DoEvents(); 27 28 IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5656); sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, 29 ProtocolType.IP); 30 sock.Bind(ipEnd); 31 sock.Listen(100); 32 Socket clientSock = sock.Accept(); 33 DataTable table = getdata(); 34 clientSock.Send(SerializeData(table));
35 36 sock.Close(); 37 clientSock.Close(); 38 startButton.Text = "&Start Server"; 39 Application.DoEvents(); 40 } 42 public byte[] SerializeData(Object o) 43 { 44 MemoryStream ms = new MemoryStream(); 45 BinaryFormatter bf1 = new BinaryFormatter(); 46 bf1.Serialize(ms, o); 47 return ms.ToArray(); 48 } 50 /* y ti to 1 bng d liu th. 51 Bn c th kt ni csdl v load d liu ln*/ 52 private DataTable getdata() 53 { 54 55 57 58 59 DataTable dt = new DataRow dr; dt.Columns.Add(new dt.Columns.Add(new dt.Columns.Add(new DataTable(); DataColumn("IntegerValue", typeof(Int32))); DataColumn("StringValue", typeof(string))); DataColumn("DateTimeValue", typeof(DateTime)));
60 dt.Columns.Add(new DataColumn("BooleanValue", typeof(bool))); 62 for (int i = 1; i <= 1000; i++) 63 { 64 dr = dt.NewRow(); 65 dr[0] = i; 66 dr[1] = "Item " + i.ToString(); 67 dr[2] = DateTime.Now; 68 dr[3] = (i % 2 != 0) ? true : false; 70 dt.Rows.Add(dr); 71 } 72 73 74 75 return dt; } } }
Bin dch chng trnh sau m th mc bin/Debug chy tp tin SocketServer.exe. Nhn nt Start Server bt u chy server. Mi ln gi xong phi nhn nt start mt ln. Bn c th dng
Threading cho n chy lin tc, tuy nhin bn s phi xem n phng thc SendAsync ca socket. 2. pha Client: Bn Thm 1 project khc c tn SocketClient vo Solution. Thm vo 1 textbox nhp server address, mt nt nhn nhn d liu. Thit k nh sau
21 InitializeComponent(); 22 } 23 24 public object DeserializeData(byte[] theByteArray) 25 { 26 MemoryStream ms = new MemoryStream(theByteArray); 27 BinaryFormatter bf1 = new BinaryFormatter(); 28 ms.Position = 0; 29 return bf1.Deserialize(ms); 30 } 31 32 private void receiveButton_Click(object sender, EventArgs e) 33 { 34 try 35 { 36 IPAddress[] ipAddress = Dns.GetHostAddresses(serverTextBox.Text); 37 IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse("127.0.0.1"),5656); 38 Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
39 clientSock.Connect(ipEnd); 40 byte[] data = new byte[1024 * 5000]; 41 clientSock.Receive(data); 42 DataTable dt = (DataTable)DeserializeData(data); 43 dataGridView1.DataSource = dt; 44 clientSock.Close(); 45 } 46 catch (Exception ex) 47 { 48 49 50 51 52 MessageBox.Show(ex.Message); } } } }
Full Source Code: download here Em p dng Threading cho Server c th kt ni vi nhiu Server v khng lm cho lp giao din b treo. Nhng v v k thut Threading em cha nm r lm, ni chung l cn rt km. Khi em nhn nt Start th n s sinh ra Thread ch yu cu ca Client. V Thread ny em mun dng kt ni vi nhiu Client nn em trong vng lp while(true), c th nh sau:
public partial class StartServer : Form { ..................................................... private void btstart_Click(object sender, EventArgs e) { new Thread(new ThreadStart(Listening)).Start(); } private void Listening() { IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2011); TcpListener server = new TcpListener(ip); server.Start(); while (true) { TcpClient client = server.AcceptTcpClient(); new SocketServer(client);
} } } class SocketServer { private TcpClient client; public SocketServer(TcpClient client) { this.client = client; new Thread(new ThreadStart(Processing)).Start(); } private void Processing() { // // X l trao i d liu vi Client // } } 01 using System; 02 using System.Threading; 03 04 public class Worker 05 { 06 // This method will be called when the thread is started. 07 public void DoWork() 08 { 09 while (!_shouldStop) 10 { 11 Console.WriteLine("worker thread: working..."); 12 } 13 Console.WriteLine("worker thread: terminating gracefully."); 14 } 15 public void RequestStop() 16 { 17 _shouldStop = true; 18 } 19 // Volatile is used as hint to the compiler that this data 20 // member will be accessed by multiple threads.
21 private volatile bool _shouldStop; 22 } 23 24 public class WorkerThreadExample 25 { 26 static void Main() 27 { 28 // Create the thread object. This does not start the thread. 29 Worker workerObject = new Worker(); 30 Thread workerThread = new Thread(workerObject.DoWork); 31 32 // Start the worker thread. 33 workerThread.Start(); 34 Console.WriteLine("main thread: Starting worker thread..."); 35 36 // Loop until worker thread activates. 37 while (!workerThread.IsAlive); 38 39 // Put the main thread to sleep for 1 millisecond to 40 // allow the worker thread to do some work: 41 Thread.Sleep(1); 42 43 // Request that the worker thread stop itself: 44 workerObject.RequestStop(); 45 46 // Use the Join method to block the current thread 47 // until the object's thread terminates. 48 workerThread.Join(); 49 Console.WriteLine("main thread: Worker thread has terminated."); 50 } 51 }
Thy gip dm em,em lm bi tp chat gia client,em thy ti liu no cng nh code trn,nhng khi em chy v nhn button listen th bo dng newsock.Bind(iep
001 public class RationalNumber
002 { 003 private int numerator, denominator; 004 005 //----------------------------------------------------------------006 // Constructor: Sets up the rational number by ensuring a nonzero 007 // denominator and making only the numerator signed. 008 //----------------------------------------------------------------009 public RationalNumber(int numer, int denom) 010 { 011 if (denom == 0) 012 denom = 1; 013 014 // Make the numerator "store" the sign 015 if (denom < 0) 016 { 017 numer = numer * -1; 018 denom = denom * -1; 019 } 020 021 numerator = numer; 022 denominator = denom; 023 024 reduce(); 025 } 026 027 //----------------------------------------------------------------028 // Returns the numerator of this rational number. 029 //----------------------------------------------------------------030 public int Numerator 031 { 032 get 033 { 034 return numerator; 035 } 036 } 037
038 //----------------------------------------------------------------039 // Returns the denominator of this rational number. 040 //----------------------------------------------------------------041 public int Denominator 042 { 043 get 044 { 045 return denominator; 046 } 047 } 048 049 //----------------------------------------------------------------050 // Returns the reciprocal of this rational number. 051 //----------------------------------------------------------------052 public RationalNumber reciprocal() 053 { 054 return new RationalNumber(denominator, numerator); 055 } 056 057 //----------------------------------------------------------------058 // Adds this rational number to the one passed as a parameter. 059 // A common denominator is found by multiplying the individual 060 // denominators. 061 //----------------------------------------------------------------062 public RationalNumber add(RationalNumber op2) 063 { 064 065 066 067 068 069 return new RationalNumber(sum, commonDenominator); 070 } 071 072 //----------------------------------------------------------------073 // Subtracts the rational number passed as a parameter from this int int int int commonDenominator = denominator * op2.Denominator; numerator1 = numerator * op2.Denominator; numerator2 = op2.Numerator * denominator; sum = numerator1 + numerator2;
074 // rational number. 075 //----------------------------------------------------------------076 public RationalNumber subtract(RationalNumber op2) 077 { 078 079 080 081 082 083 return new RationalNumber(difference, commonDenominator); 084 } 085 086 //----------------------------------------------------------------087 // Multiplies this rational number by the one passed as a 088 // parameter. 089 //----------------------------------------------------------------090 public RationalNumber multiply(RationalNumber op2) 091 { 092 int numer = numerator * op2.Numerator; 093 int denom = denominator * op2.Denominator; 094 095 return new RationalNumber(numer, denom); 096 } 097 098 //----------------------------------------------------------------099 // Divides this rational number by the one passed as a parameter 100 // by multiplying by the reciprocal of the second rational. 101 //----------------------------------------------------------------102 public RationalNumber divide(RationalNumber op2) 103 { 104 return multiply(op2.reciprocal()); 105 } 106 107 //----------------------------------------------------------------108 // Determines if this rational number is equal to the one passed 109 // as a parameter. Assumes they are both reduced. int int int int commonDenominator = denominator * op2.Denominator; numerator1 = numerator * op2.Denominator; numerator2 = op2.Numerator * denominator; difference = numerator1 - numerator2;
110 //----------------------------------------------------------------111 public override bool Equals(object obj) 112 { 113 RationalNumber op2 = (RationalNumber)obj; 114 return (numerator == op2.Numerator && 115 denominator == op2.Denominator); 116 } 117 118 //----------------------------------------------------------------119 // Returns this rational number as a string. 120 //----------------------------------------------------------------121 public String toString() 122 { 123 String result; 124 125 if (numerator == 0) 126 result = "0"; 127 else 128 if (denominator == 1) 129 result = numerator + ""; 130 else 131 result = numerator + "/" + denominator; 132 133 return result; 134 } 135 136 //----------------------------------------------------------------137 // Reduces this rational number by dividing both the numerator 138 // and the denominator by their greatest common divisor. 139 //----------------------------------------------------------------140 private void reduce() 141 { 142 if (numerator != 0) 143 { 144 int common = gcd(Math.Abs(numerator), denominator); 145
146 numerator = numerator / common; 147 denominator = denominator / common; 148 } 149 } 150 151 //----------------------------------------------------------------152 // Computes and returns the greatest common divisor of the two 153 // positive parameters. Uses Euclid's algorithm. 154 //----------------------------------------------------------------155 private int gcd(int num1, int num2) 156 { 157 while (num1 != num2) 158 if (num1 > num2) 159 num1 = num1 - num2; 160 else 161 num2 = num2 - num1; 162 163 return num1; 164 } 165 }
thy cho em hi: em lm game c vua chi qua mng client bng wpf, em to mng client chat c vi nhau.nhng khi n new game th n b n doi hm Case khng nhn ra cu lnh m . em gn gi tri khi n new game =sendPacket(N). thy c th sa cho em c khg ah private void SendData(IAsyncResult iar) { Socket remote = (Socket)iar.AsyncState; int sent = remote.EndSend(iar); } public void sendPacket(string packet) { try { byte[] Sent = Encoding.ASCII.GetBytes(packet); socket.BeginSend(Sent, 0, Sent.Length, 0, new AsyncCallback(SendData), socket);
} catch (SocketException e) { state = StateConnection.Breaken; } } private void ReceiveData() { int recv; string packData = ; try { while (true) { recv = socket.Receive(data); packData = Encoding.ASCII.GetString(data, 0, recv); if (packData.ToString().Equals()) return; if (packData.StartsWith(@)) { AddChatMessage(packData.ToString()); } else { switch (packData.ToString()) { case N: { SetStatusMessage1(Ngi chi sn sng!); batdau(); } break; case X: { SetStatusMessage1(Ngi chi thot game!); //oat();
Trong lp trnh, Socket l mt API (Application Programming Interface) cung cp cc phng thc giao tip thng qua mng. Trc khi bt u tm hiu v vit mt v d n gin v socket, bn c th tham kho bi vit Networking Mt s khi nim c bn c ci nhn s lc v nhng khi nim c bn trong lp trnh mng.
Kt ni Server-Client vi TCP/IP
Khi c chy, server cn c xc nh r a ch IP v s lng nghe trn mt port c th. Server s nm trong trng thi ny cho n khi client gi n mt yu cu kt ni. Sau khi c server chp nhn, mt connection s hnh thnh cho php server v client giao tip vi nhau. C th hn, cc bc tin hnh trn server v client m ta cn thc hin s dng giao thc TCP/IP trong C# (c th chy server v client trn cng mt my): Server:
1. 2.
3. 4.
To mt i tng System.Net.Sockets.TcpListener bt u lng nghe trn mt i v chp nhn kt ni t client vi phng thc AccepSocket(). Phng thc ny tr Thc hin giao tip vi client. ng Socket.
Thng thng quy trnh ny s c t trong mt vng lp (lp li bc 2) chp nhn nhiu kt ni cng lc (s dng Thread) hoc cc kt ni ln lt. Client:
1.
2.
3. 4. 5.
Ly lung (stream) giao tip bng phng thc TcpClient.GetStream(). Thc hin giao tip vi server. ng lung v socket.
Y2Server.cs (v1):
view source print?
01 using System; 02 using System.Text; 03 using System.Net; 04 using System.Net.Sockets; 05 06 public class Y2Server { 07 08 private const int BUFFER_SIZE=1024; 09 private const int PORT_NUMBER=9999; 10 11 static ASCIIEncoding encoding=new ASCIIEncoding(); 12 13 public static void Main() { 14 try { 15 IPAddress address = IPAddress.Parse("127.0.0.1"); 16 17 TcpListener listener=new TcpListener(address,PORT_NUMBER); 18 19 // 1. listen 20 listener.Start(); 21 22 Console.WriteLine("Server started on "+listener.LocalEndpoint); 23 Console.WriteLine("Waiting for a connection..."); 24 25 Socket socket=listener.AcceptSocket(); 26 Console.WriteLine("Connection received from " + socket.RemoteEndPoint); 27 28 // 2. receive 29 byte[] data=new byte[BUFFER_SIZE]; 30 socket.Receive(data); 31 32 string str=encoding.GetString(data);
33 34 // 3. send 35 socket.Send(encoding.GetBytes("Hello "+str)); 36 37 // 4. close 38 socket.Close(); 39 listener.Stop(); 40 41 } 42 catch (Exception ex) { 43 Console.WriteLine("Error: " + ex); 44 } 45 Console.Read(); 46 } 47 }
Y2Client.cs (v1):
view source print?
01 using System; 02 using System.IO; 03 using System.Net; 04 using System.Text; 05 using System.Net.Sockets; 06 07 public class Y2Client{ 08 09 private const int BUFFER_SIZE=1024; 10 private const int PORT_NUMBER=9999; 11 12 static ASCIIEncoding encoding= new ASCIIEncoding(); 13 14 public static void Main() { 15 16 try { 17 TcpClient client = new TcpClient(); 18
19 // 1. connect 20 client.Connect("127.0.0.1",PORT_NUMBER); 21 Stream stream = client.GetStream(); 22 23 Console.WriteLine("Connected to Y2Server."); 24 Console.Write("Enter your name: "); 25 26 string str = Console.ReadLine(); 27 28 // 2. send 29 byte[] data=encoding.GetBytes(str); 30 31 stream.Write(data,0,data.Length); 32 33 // 3. receive 34 data =new byte[BUFFER_SIZE]; 35 stream.Read(data,0,BUFFER_SIZE); 36 37 Console.WriteLine(encoding.GetString(data)); 38 39 // 4. Close 40 stream.Close(); 41 client.Close(); 42 } 43 44 catch (Exception ex) { 45 Console.WriteLine("Error: " + ex); 46 } 47 48 Console.Read(); 49 } 50 }
kim tra v d, bn chy server trc, ca s console ca server s hin th: Server started on 127.0.0.1:9999 Waiting for a connection Tip n cho chy client, nu kt ni thnh cng, server s hin th thm dng thng bo tng t nh sau: Connection received from 127.0.0.1:2578
Chuyn qua ca s console ca client v nhp tn ca bn vo, nu nhn c d liu, server s gi tr li dng thng ip Hello [Your Name] Connected to Y2Server. Enter your name: Yin Yang Hello Yin Yang Ngay sau bc ny, c server v client u thc hin ng kt ni.
01 using System; 02 using System.IO; 03 using System.Net; 04 using System.Net.Sockets; 05 using System.Text; 06 07 public class Y2Server { 08 09 private const int BUFFER_SIZE=1024; 10 private const int PORT_NUMBER=9999; 11 12 static ASCIIEncoding encoding=new ASCIIEncoding(); 13 14 public static void Main() { 15 try { 16 IPAddress address = IPAddress.Parse("127.0.0.1"); 17 18 TcpListener listener=new TcpListener(address,PORT_NUMBER); 19 20 // 1. listen 21 listener.Start(); 22 23 Console.WriteLine("Server started on "+listener.LocalEndpoint); 24 Console.WriteLine("Waiting for a connection...");
25 26 Socket socket=listener.AcceptSocket(); 27 Console.WriteLine("Connection received from " + socket.RemoteEndPoint); 28 29 var stream = new NetworkStream(socket); 30 var reader=new StreamReader(stream); 31 var writer=new StreamWriter(stream); 32 writer.AutoFlush=true; 33 34 while(true) 35 { 36 // 2. receive 37 string str=reader.ReadLine(); 38 if(str.ToUpper()=="EXIT") 39 { 40 writer.WriteLine("bye"); 41 break; 42 } 43 // 3. send 44 writer.WriteLine("Hello "+str); 45 } 46 47 48 49 // 4. close stream.Close(); socket.Close(); listener.Stop();
05 using System.Net.Sockets; 06 07 public class Y2Client{ 08 09 private const int BUFFER_SIZE=1024; 10 private const int PORT_NUMBER=9999; 11 12 static ASCIIEncoding encoding= new ASCIIEncoding(); 13 14 public static void Main() { 15 16 try { 17 TcpClient client = new TcpClient(); 18 19 // 1. connect 20 client.Connect("127.0.0.1",PORT_NUMBER); 21 Stream stream = client.GetStream(); 22 23 Console.WriteLine("Connected to Y2Server."); 24 while(true) 25 { 26 Console.Write("Enter your name: "); 27 28 29 30 31 32 33 // 2. send 34 writer.WriteLine(str); 35 36 // 3. receive 37 str=reader.ReadLine(); 38 Console.WriteLine(str); 39 if(str.ToUpper()=="BYE") 40 break; string str = Console.ReadLine(); var reader=new StreamReader(stream); var writer=new StreamWriter(stream); writer.AutoFlush=true;
SocketTCP - Chat qua l i gi a Client v Server. Chy trn cng mt my nh. Nu 2 my tnh chnh IPEnpoint li. Trn client g date server tr v ngy thng nm. G byby thot server v client Server: Code:
using using using using using System; System.Collections.Generic; System.Text; System.Net; System.Net.Sockets;
namespace SocketServer { class Program { static void Main(string[] args) { Console.WriteLine("-----------------------Server-----------------------------"); Console.WriteLine(" Chuong trinh chat 2 may voi nhau "); Console.WriteLine(" Luu y: 1 ben goi va ben kia phai tra loi moi goi tiep duoc"); Console.WriteLine("----------------------------------------------------------"); Console.WriteLine("---------------------Sunboy-2mit.org----------------------");
//tao soc ket IPEndPoint ipserver = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5302); Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //bind server.Bind(ipserver); //listen server.Listen(10); Console.WriteLine("Chuan bi ket noi!"); Socket client = server.Accept(); Console.WriteLine("Chap nhan ket noi tu: {0}",client.RemoteEndPoint.ToString()); // string s; byte[] data = new byte[1024]; string s = "Ket noi thanh cong den Server. Bat dau chat"; //Chuyen chuoi s thanh mang byte //byte[] data = new byte[1024]; data = Encoding.ASCII.GetBytes(s); client.Send(data,data.Length,SocketFlags.None); string input; while (true) { data = new byte[1024]; int nhan = client.Receive(data);
s = Encoding.ASCII.GetString(data,0,nhan); if (s.Equals("byby")) break; Console.WriteLine("Client: {0}",s); input = Console.ReadLine(); data = new byte[1024]; data = Encoding.ASCII.GetBytes(input); client.Send(data, data.Length, SocketFlags.None); } client.Shutdown(SocketShutdown.Both); client.Close(); server.Close(); } } }
Client: Code:
using System; using System.Collections.Generic;
using System.Text; using System.Net; using System.Net.Sockets; namespace SocketClient { class Program { static void Main(string[] args) { Console.WriteLine("------------------------Client------------------------"); Console.WriteLine(" Chuong trinh chat 2 may voi nhau "); Console.WriteLine(" Luu y: 1 ben goi va ben kia phai tra loi moi goi tiep duoc"); Console.WriteLine("----------------------------------------------------------"); Console.WriteLine("---------------------Sunboy-2mit.org----------------------"); //int a; //int p; IPEndPoint ipenpointclient = new IPEndPoint(IPAddress.Parse("127.0.0.1"),5302); //IPEndPoint ipenpointclient = new IPEndPoint(a, 5302); //Console.WriteLine("Moi nhap ip server: "); //Console.ReadLine(IPAddress.Parse(a)); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(ipenpointclient); byte[] data = new byte[1024]; int nhan = client.Receive(data); // data = "Chao client"; string s = Encoding.ASCII.GetString(data,0,nhan); Console.WriteLine(s); string input; string ngay; while (true) { input = Console.ReadLine(); data = new byte[1024]; data = Encoding.ASCII.GetBytes(input); client.Send(data,data.Length,SocketFlags.None); data = new byte[1024]; nhan = client.Receive(data); s = Encoding.ASCII.GetString(data, 0, nhan);
if (s.Equals("getdate")) { input = DateTime.Now.ToString("dd/MM/yyyy"); data = new byte[1024]; data = Encoding.ASCII.GetBytes(input); client.Send(data, data.Length, SocketFlags.None); } if (s.Equals("byby") || input.Equals("byby")) break; Console.WriteLine("Server: {0}",s); } client.Disconnect(true); client.Close(); } } }