TcpClient创建网络连接

来源:互联网 发布:xin域名值钱多少钱 编辑:程序博客网 时间:2024/05/05 21:37

用TcpClient创建简单的服务端和客户端程序


服务器端的控制台应用程序

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net.Sockets;using System.Net;namespace Server{    class Program    {        static void Main(string[] args)        {   //创建一个tcpListener对象,此对象主要是对给定端口进行侦听            TcpListener tcpListener = new TcpListener(1234);            //开始侦听            tcpListener.Start();            //返回可以用以处理链接的Socket实例            Socket socketForClient = tcpListener.AcceptSocket();            try            {                //使用Connected属性,判断是否连接成功                if (socketForClient.Connected)                {                    Console.WriteLine("已经和客户端连接成功!");                }            }            catch (Exception ex)            {                Console.WriteLine(ex.Message );            }        }    }}



简单的客户端控制台应用程序


using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net.Sockets;using System.Net;namespace Server{    class Program    {        static void Main(string[] args)        {            try            {                //创建一个TcpClient对象,设置连接服务器的IP和端口号                TcpClient myclient = new TcpClient("localhost", 1234);            }            catch            {                Console.WriteLine("没有连接到服务器!");            }        }    }}



0 0
原创粉丝点击