存档

文章标签 ‘socket’

同步模式下的流套接字Socket编程

2009年4月30日

本文介绍同步模式下的流套接字Socket编程,关于Socket通信的原理在前一篇文章中已经介绍了,在此就不多说了,仅以例子进行说明
Server端:接收数据,并显示,同时反馈给客户端信息,程序是多线程的

?Download PcSocket.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
 
namespace test.socket
{
    class PcSocket
    {
        //private Socket server;
        private int SERVER_PORT=9696;//侦听端口
        private string SERVER_IP = "222.195.151.223";//服务器地址
        private static int BUFFER_SIZE = 65535;//设置缓冲区大小
        public PcSocket() {
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipadd = IPAddress.Parse(SERVER_IP);            
            IPEndPoint ipe = new IPEndPoint(ipadd, SERVER_PORT);
            server.Bind(ipe);
            server.Listen(100);
            Console.WriteLine("wait for the client to build Connection……");
            while (true) {
                Socket client = server.Accept();//阻塞方法,创建新的连接
                ClientThread newClient = new ClientThread(client);//创建了ClientThread类的实例
                Thread newThread = new Thread(new ThreadStart(newClient.ClientServer));//新建线程,并将ClientThread类的实例的方法赋给线程
                newThread.Start();//启动线程
            }
 
        }
        class ClientThread {           
            private Socket client;
            private string data = null;
            private byte[] receiveBytes = new byte[BUFFER_SIZE];//服务器端设置缓冲区
            int i;
            private int bytesCount;
            public ClientThread(Socket ClientSocket) {
                this.client = ClientSocket;
            }
            public void ClientServer() {     
 
                try
                {
                    bytesCount = client.Receive(receiveBytes, receiveBytes.Length, 0);//从客户端接收信息
                    if (bytesCount != 0)//当服务器端的缓冲区接收到的信息不为空时
                    {
                        data = Encoding.ASCII.GetString(receiveBytes, 0, bytesCount);
                        Console.WriteLine("Receive date:{0}", data);
                        string sendStr = "OK!Client send message sucessfully";
                        byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);
                        client.Send(sendBytes, sendBytes.Length, 0);//向客户端发送信息                        
                    }
                }
                catch (Exception ex)
                {
                    Console.Write("出现异常:");
                    Console.WriteLine(ex.ToString());
                    Console.ReadLine();
                } 
                client.Close();               
            }
        }
    }
}

Client端:发送数据,并接收服务器端反馈的信息,进行显示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace testClient.client
{
    class ClientSocket
    {
        private int SERVER_PORT = 9696;
        private string SERVER_IP = "222.195.151.223";
        private static int BUFFER_SIZE = 65535;
        private Socket client = null; //客户端套接字        
        private string clientInput; // 输入的字符串
        private string clientReceiveStr=null;//接收到的字符串
        private byte[] clientSendBytes = new byte[BUFFER_SIZE];
        private byte[] clientReceiveBytes = new byte[BUFFER_SIZE];
        public ClientSocket()
        {            
            try
            {      
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                
                IPAddress ipadd = IPAddress.Parse(SERVER_IP);
                IPEndPoint ipe = new IPEndPoint(ipadd, SERVER_PORT);                
                client.Connect(ipe);               
            }
            catch (SocketException se)
            {
                Console.WriteLine("服务器程序尚未启动!请先启动服务器程序!");
                Console.WriteLine("Error occurs:" + se.ToString());
                Console.ReadLine();
            }          
            if (client.Connected) //如果与服务器已经建立连接
            {
                try
                {                    
                    clientInput = "hello,this is a socket test";                    
                    clientSendBytes = Encoding.ASCII.GetBytes(clientInput);                    
                    //Send方法返回一个System.Int32类型的值,表明已发送数据的大小
                    client.Send(clientSendBytes, clientSendBytes.Length, 0);                    
                    int bytes = client.Receive(clientReceiveBytes, clientReceiveBytes.Length, 0);//从服务器端接受返回信息
                    clientReceiveStr = Encoding.ASCII.GetString(clientReceiveBytes, 0, bytes);
                    Console.WriteLine("client get message:{0}", clientReceiveStr);//显示服务器返回信息                   
                }
                catch (Exception ex)
                {
                    Console.Write("出现异常:");
                    Console.WriteLine(ex.ToString());
                    Console.ReadLine();
                }             
                client.Shutdown(SocketShutdown.Both);
                client.Close();
                Console.ReadLine();
 
            }
 
        }
 
    }
}

C#学习, 移动平台 ,