码迷,mamicode.com
首页 > 其他好文 > 详细

C#网络通信

时间:2014-08-14 19:38:39      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   ar   art   

Server:

using System.Net;
using System.Net.Sockets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ServerConsole
{
    class Server
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Server is runing...");
            IPAddress ip = new IPAddress(new byte[]{127,0,0,1});
            TcpListener listener = new TcpListener(ip, 8500);

            listener.Start();//开始侦听
            while (true)
            {
                //获取一个连接,中断方法
                TcpClient remoteClient = listener.AcceptTcpClient();
                //打印连接客户端的信息
                Console.WriteLine("Client Connected!{0}---->{1}", remoteClient.Client.LocalEndPoint,remoteClient.Client.RemoteEndPoint);
            }
        }
    }
}

Client:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace ClientConsole
{
    class Client
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Client is running...");
            TcpClient client = null;

            for (int i = 0; i < 3; i++)
            {
                client = new TcpClient();
                try
                {
                    //与服务器建立连接
                    client.Connect("localhost", 8500); ;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception occured.." + ex.Message);
                    return;
                }
            
                //输出已连接到服务器
                Console.WriteLine("Server Connected!{0}-->{1}",
                client.Client.LocalEndPoint, client.Client.RemoteEndPoint);
            }
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key; 
            } while (key != ConsoleKey.Q);
        }
    }
}

 

C#网络通信,布布扣,bubuko.com

C#网络通信

标签:style   blog   color   os   io   for   ar   art   

原文地址:http://www.cnblogs.com/cause/p/3912824.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!