C#聊天程序

C#编写简单的聊天程序 引言这是一篇基于Socket进行网络编程的入门文章,我对于网络编程的学习并不够深入,这篇文章是对于自己知识的一个巩固,同时希望能为初学的朋友提供一点参考。文章大体分为四个部分:程序的分析与设计、C#网络编程基础(篇外篇)、聊天程序的实现模式、程序实现。程序的分析与设计1.明确程序功能如果大家现在已经参加了工作,你的经理或者老板告诉你,“小王,我需要你开发一个聊天程序”。那么接下来该 阅读详情

/*=====================================================================
  文件:      Wintalk.cs

  摘要:   演示如何使用 .NET创建聊天程序

=====================================================================*/

using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Drawing;
using System.Windows.Forms;

class App{       
    // Entry point
    public static void Main(String[] args){       
        // If the args parse in known way then run the app
        if(ParseArgs(args)){          
            // Create a custom Talker object
            Talker talker = new Talker(endPoint, client);
            // Pass the object reference to a new form object
            TalkForm form = new TalkForm(talker);                  
            // Start the talker "talking"
            talker.Start();

            // Run the applications message pump
            Application.Run(form);
        }       
    }

    // Parsed Argument Storage
    private static IPEndPoint endPoint;
    private static bool client;

    // Parse command line arguments
    private static bool ParseArgs(String[] args){
        try{       
            if(args.Length == 0){
                client = false;
                endPoint = new IPEndPoint(IPAddress.Any,5150);
                return true;
            }

            switch(Char.ToUpper(args[0][1])){
            case 'L':
                int port = 5150;
                if(args.Length > 1){
                   port = Convert.ToInt32(args[1]);   
                }
                endPoint = new IPEndPoint(IPAddress.Any,port);
                client = false;
                break;
            case 'C':
                port = 5150;
                String address = "127.0.0.1";
                client = true;
                if(args.Length > 1){
                    address = args[1];
                    port = Convert.ToInt32(args[2]);                                       
                }               
                endPoint = new IPEndPoint(Dns.Resolve(address).AddressList[0], port);
                break;
            default:
                ShowUsage();
                return false;
            }
        }catch{
            ShowUsage();
            return false;
        }   
   
        return true;
    }

    // Show sample usage
    private static void ShowUsage(){
        MessageBox.Show("WinTalk [switch] [parameters...]/n/n"+
            "  /L  [port]/t/t-- Listens on a port.  Default:  5150/n"+
            "  /C  [address] [port]/t-- Connects to an address and port./n/n"+
            "Example Server - /n"+
            "Wintalk /L/n/n"+
            "Example Client - /n"+
            "Wintalk /C ServerMachine 5150","WinTalk Usage");
    }
}

// UI class for the sample
class TalkForm:Form {   
    public TalkForm(Talker talker) {
        // Associate for method with the talker object
        this.talker = talker;
        talker.Notifications += new
                Talker.NotificationCallback(HandleTalkerNotifications);

        // Create a UI elements
        Splitter talkSplitter = new Splitter();
        Panel talkPanel = new Panel();       

        receiveText = new TextBox();
        sendText = new TextBox();
       
        // we'll support up to 64k data in our text box controls
        receiveText.MaxLength = sendText.MaxLength = 65536;
        statusText = new Label();
    
        // Initialize UI elements
        receiveText.Dock = DockStyle.Top;
        receiveText.Multiline = true;
        receiveText.ScrollBars = ScrollBars.Both;
        receiveText.Size = new Size(506, 192);
        receiveText.TabIndex = 1;
        receiveText.Text = "";
        receiveText.WordWrap = false;
        receiveText.ReadOnly = true;
       
        talkPanel.Anchor = (AnchorStyles.Top|AnchorStyles.Bottom
                    |AnchorStyles.Left|AnchorStyles.Right);
        talkPanel.Controls.AddRange(new Control[] {sendText,
                    talkSplitter,
                    receiveText});
        talkPanel.Size = new Size(506, 371);
        talkPanel.TabIndex = 0;

        talkSplitter.Dock = DockStyle.Top;
        talkSplitter.Location = new Point(0, 192);
        talkSplitter.Size = new Size(506, 6);
        talkSplitter.TabIndex = 2;
        talkSplitter.TabStop = false;
       
        statusText.Dock = DockStyle.Bottom;
        statusText.Location = new Point(0, 377);
        statusText.Size = new Size(507, 15);
        statusText.TabIndex = 1;
        statusText.Text = "Status:";

        sendText.Dock = DockStyle.Fill;
        sendText.Location = new Point(0, 198);
        sendText.Multiline = true;
        sendText.ScrollBars = ScrollBars.Both;
        sendText.Size = new Size(506, 173);
        sendText.TabIndex = 0;
        sendText.Text = "";
        sendText.WordWrap = false;
        sendText.TextChanged += new EventHandler(HandleTextChange);
        sendText.Enabled = false;

        AutoScaleBaseSize = new Size(5, 13);
        ClientSize = new Size(507, 392);
        Controls.AddRange(new Control[] {statusText,
                    talkPanel});
        Text = "WinTalk";

        this.ActiveControl = sendText;    
    }   

    // When the app closes, dispose of the talker object
    protected override void OnClosed(EventArgs e){
        if(talker!=null){
            // remove our notification handler
            talker.Notifications -= new
                Talker.NotificationCallback(HandleTalkerNotifications);
           
            talker.Dispose();
        }
        base.OnClosed(e);
    }
   
    // Handle notifications from the talker object
    private void HandleTalkerNotifications(
        Talker.Notification notify, Object data){
        switch(notify){
        case Talker.Notification.Initialized:
            break;
        // Respond to status changes
        case Talker.Notification.StatusChange:
            Talker.Status status = (Talker.Status)data;
            statusText.Text = String.Format("Status: {0}", status);
            if(status == Talker.Status.Connected){
                sendText.Enabled = true;
            }
            break;
        // Respond to received text
        case Talker.Notification.Received:
            receiveText.Text = data.ToString();
            receiveText.SelectionStart = Int32.MaxValue;
            receiveText.ScrollToCaret();       
            break;
        // Respond to error notifications
        case Talker.Notification.Error:           
            Close(data.ToString());       
            break;
        // Respond to end
        case Talker.Notification.End:                                   
            MessageBox.Show(data.ToString(), "Closing WinTalk");            
            Close();
            break;
        default:
            Close();
            break;
        }
    }

    // Handle text change notifications and send talk
    private void HandleTextChange(Object sender, EventArgs e){
        if(talker != null){
            talker.SendTalk((sender as TextBox).Text);
        }       
    }  

    // Close with an explanation
    private void Close(String message){  
        MessageBox.Show(message, "Error!");       
        Close();
    }

    // Private UI elements
    private TextBox receiveText;       
    private TextBox sendText;   
    private Label statusText;
    private Talker talker;  
}

// An encapsulation of the Sockets class used for socket chatting
class Talker:IDisposable{
    // Construct a talker
    public Talker(IPEndPoint endPoint, bool client){
        this.endPoint = endPoint;
        this.client = client;

        socket = null;
        reader = null;
        writer = null;

        statusText = prevSendText = prevReceiveText = String.Empty;
    }

    // Finalize a talker
    ~Talker(){
        Dispose();
    }

    // Dispose of resources and surpress finalization
    public void Dispose(){       
        GC.SuppressFinalize(this);
        if(reader != null){
            reader.Close();
            reader = null;
        }
        if(writer != null){
            writer.Close();
            writer = null;
        }
        if(socket != null){
            socket.Close();
            socket = null;
        }       
    }

    // Nested delegat class and matchine event
    public delegate
       void NotificationCallback(Notification notify, Object data);
    public event NotificationCallback Notifications;

    // Nested enum for notifications
    public enum Notification{
        Initialized = 1,
        StatusChange,
        Received,
        End,
        Error
    }

    // Nested enum for supported states
    public enum Status{
        Listening,
        Connected
    }

    // Start up the talker's functionality
    public void Start(){
        ThreadPool.QueueUserWorkItem(new WaitCallback(EstablishSocket));
    }

    // Send text to remote connection
    public void SendTalk(String newText){               
        String send;
        // Is this an append
        if((prevSendText.Length <= newText.Length) && String.CompareOrdinal(
            newText, 0, prevSendText, 0, prevSendText.Length)==0){
            String append = newText.Substring(prevSendText.Length);
            send = String.Format("A{0}:{1}", append.Length, append);
        // or a complete replacement
        }else{
            send = String.Format("R{0}:{1}", newText.Length, newText);
        }  
        // Send the data and flush it out
        writer.Write(send);
        writer.Flush();
        // Save the text for future comparison
        prevSendText = newText;
    }

    // Send a status notification
    private void SetStatus(Status status){
        this.status = status;
        Notifications(Notification.StatusChange, status);
    }

    // Establish a socket connection and start receiving
    private void EstablishSocket(Object state){              
        try{
            // If not client, setup listner
            if(!client){
                Socket listener;
               
                try{
                    listener = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);
                    listener.Blocking = true;
                    listener.Bind(endPoint);
                    SetStatus(Status.Listening);                   
                    listener.Listen(0);
                    socket = listener.Accept();
                    listener.Close();                               
                }catch(SocketException e){
                    // If there is already a listener on this port try client
                    if(e.ErrorCode == 10048){
                        client = true;
                        endPoint = new IPEndPoint(
                            Dns.Resolve("127.0.0.1").AddressList[0], endPoint.Port);
                    }else{
                        Notifications(
                            Notification.Error,
                            "Error Initializing Socket:/n"+e.ToString());                       
                    }
                }                                   
            }

            // Try a client connection
            if(client){
                Socket temp = new
                    Socket(AddressFamily.InterNetwork,
                    SocketType.Stream,ProtocolType.Tcp);
                temp.Blocking = true;
                temp.Connect(endPoint);
                socket = temp;
            }

            // If it all worked out, create stream objects
            if(socket != null){
                SetStatus(Status.Connected);                
                NetworkStream stream = new NetworkStream(socket);
                reader = new StreamReader(stream);
                writer = new StreamWriter(stream);
                Notifications(Notification.Initialized, this);               
            }else{
                Notifications(Notification.Error,
                    "Failed to Establish Socket");
            }

            // Start receiving talk
            // Note: on w2k and later platforms, the NetworkStream.Read()
            // method called in ReceiveTalk will generate an exception when
            // the remote connection closes. We handle this case in our
            // catch block below.
            ReceiveTalk();

            // On Win9x platforms, NetworkStream.Read() returns 0 when
            // the remote connection closes, prompting a graceful return
            // from ReceiveTalk() above. We will generate a Notification.End
            // message here to handle the case and shut down the remaining
            // WinTalk instance.
            Notifications(Notification.End, "Remote connection has closed.");
           
        }catch(IOException e){
            SocketException sockExcept = e.InnerException as SocketException;
            if(sockExcept != null && 10054 == sockExcept.ErrorCode){
                Notifications(Notification.End, "Remote connection has closed.");
            }else{
    if (Notifications != null)
     Notifications(Notification.Error, "Socket Error:/n"+e.Message);
            }               
        }catch(Exception e){             
            Notifications(Notification.Error, "Socket Error:/n"+e.Message);
        }
    }

    // Receive chat from remote client
    private void ReceiveTalk(){
        char[] commandBuffer = new char[20];
        char[] oneBuffer = new char[1];
        int readMode = 1;
        int counter = 0;       
        StringBuilder text = new StringBuilder();

        while(readMode != 0){
            if(reader.Read(oneBuffer, 0, 1)==0){
                readMode = 0;
                continue;
            }

            switch(readMode){
            case 1:       
                if(counter == commandBuffer.Length){
                    readMode = 0;
                    continue;
                }
                if(oneBuffer[0] != ':'){
                    commandBuffer[counter++] = oneBuffer[0];
                }else{
                    counter = Convert.ToInt32(
                        new String(commandBuffer, 1, counter-1));
                    if(counter>0){
                        readMode = 2;                           
                        text.Length = 0;
                    }else if(commandBuffer[0] == 'R'){
                        counter = 0;
                        prevReceiveText = String.Empty;
                        Notifications(Notification.Received, prevReceiveText);
                    }
                }
                break;
            case 2:
                text.Append(oneBuffer[0]);
                if(--counter == 0){
                    switch(commandBuffer[0]){
                    case 'R':
                        prevReceiveText = text.ToString();
                        break;
                    default:
                        prevReceiveText += text.ToString();
                        break;
                    }                   
                    readMode = 1;

                    Notifications(Notification.Received, prevReceiveText);                   
                }
                break;
            default:
                readMode = 0;
                continue;
            }           
        }       
    }

    private Socket socket;

    private TextReader reader;
    private TextWriter writer;
   
    bool client;
    IPEndPoint endPoint;

    private String prevSendText;
    private String prevReceiveText;
    private String statusText;

    private Status status;   
}

Microsoft.NET FrameworkSDK带这个例子.

c# 实现socket 聊天程序 互发消息 在学期末的时候,老师正好让做一个操作系统课程设计,我选做的是socket通信 。啥也别说了 直入正题 本文就向大家介绍一下 C#下实现套接字(Sockets)编程的一些基本知识,以期能使大家对此有个大致了解。首先,我向大家介绍一下套接字的概念。 套接字基本概念:    套接字是通信的基石,是支持TCP/IP协议的网络通信的基本操作单元。可以将套接字看作不同主机间的进程进行双向通信的端 阅读详情

相关推荐

微信小程序|基于小程序+C#制作一个聊天系统

此文主要基于小程序+C#使用WebSocket制作一个聊天系统,基本实现小程序与服务端的聊天功能。用小程序自带的客服功能只能绑定微信且一对一沟通,接入市面上成熟的即时通讯预算又略显不足,干脆自己开发一个也能应对简单的业务场景。

商务合作 / 项目定制 / 学习交流。个人vx:lovely_wml 1万+

C#编写简单的聊天程序 这是一篇基于Socket进行网络编程的入门文章,我对于网络编程的学习并不够深入,这篇文章是对于自己知识的一个巩固,同时希望能为初学的朋友提供一点参考。文章大体分为四个部分:程序的分析与设计、C#网络编程基础(篇外篇)、聊天程序的实现模式、程序实现。里面有代码

包含几个关于socket传输的说明介绍文档,里面有代码 class Server { static void Main(string[] args) { const int BufferSize = 8192; // 缓存大小,8192字节 Console.WriteLine("Server is running ... "); IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 }); TcpListener listener = new TcpListener(ip, 8500);//服务器 listener.Start(); // 开始侦听 Console.WriteLine("Start Listening ..."); // 获取一个连接,中断方法 客户端 TcpClient remoteClient = listener.AcceptTcpClient();//阻塞方法 // 打印连接到的客户端信息 Console.WriteLine("Client Connected!{0} <-- {1}", remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint); // 获得流,并写入buffer中 NetworkStream streamToClient = remoteClient.GetStream(); byte[] buffer = new byte[BufferSize]; int bytesRead = streamToClient.Read(buffer, 0, BufferSize); Console.WriteLine("Reading data, {0} bytes ...", bytesRead); // 获得请求的字符串 string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead); Console.WriteLine("Received: {0}", msg); // 按Q退出 } }

C#实现的Socket基础聊天程序实战

本文还有配套的精品资源,点击获取 简介:网络通信是软件开发的关键部分,特别是在分布式系统和实时应用中。C#作为.NET编程语言,结合Socket库,可以实现基础的聊天通信程序。本文详细介绍了如何利用C#编写一个简单的聊天程序,包括服务器端的监听和客户端的连接处理,数据的发送和接收,以及字符串与字节流之间的转换。文章还提供了增强聊天体验的特性建议,如多线程处理、错误处理和用户...

weixin_35752645的博客 1141

c#聊天软件

做一个即时聊天软件 需要:本地服务器 mssqlserver ,工具:visual studio 2017 A,注册,2种方式,1,用多个groupbox把密码放在最后填写,2,直接填写密码,给出账号,资料后续自己填写。 Point1:picturebox 图片框点击时,弹出一个模态窗口,选完图片后关闭,然后窗口 有listview 大图标,imagelist,imagelist绑定listvie...

while(True): print('adorable') 1729

.NET 聊天软件,使用 WebSocket 和 H5 开发即时通讯软件,Web 网页聊天系统

使用 asp.net + websocket + h5 开发一个简单的即时通讯软件。

KeiSoft 2308

C#聊天程序设计实战指南

本文还有配套的精品资源,点击获取 简介:本文详细介绍了如何使用C#语言设计一个功能完善的聊天程序,涵盖了网络通信、多线程、用户界面设计等关键概念。通过C#的命名空间和类实现TCP/UDP协议通信、套接字编程、多线程处理、UI设计、数据序列化、安全性、状态管理、异常处理、性能优化及测试调试,构建了一个稳定和用户友好的聊天应用。 1. C#编程语言特性 C#(读作“...

weixin_42418754的博客 1071

关于使用VB.NET开发聊天软件

模仿微信聊天界面的设计理念,可利用 Windows Forms 提供的各种控件构建图形化用户界面 (GUI)。虽然原引用提到的是 Android 平台上的 XML 定义方式,但在 .NET 环境下我们更多依赖于 Visual Studio 的设计器工具或者手动编写 XAML(如果选用 WPF 技术栈的话)。考虑到长期保存会话记录的需求,应该考虑数据库解决方案如 SQLite、MySQL 或 SQL Server Express Edition 来管理用户的联系人信息及历史对话等内容。

cncbook1979的博客 409

C#Socket通讯聊天完整代码

Socket TCP/UDP聊天通讯

风凌的博客 1615

C#编程实现基础聊天室应用程序

C#(发音为 "See Sharp")是一种现代、面向对象、类型安全的编程语言,由微软公司在2000年随.NET框架一同发布。它继承了C和C++的语法风格,同时加入了.NET平台特有的功能和特性,如垃圾回收和类型安全。C#广泛应用于企业级应用程序、游戏开发(通过Unity引擎)、Web服务和API等。消息通常包含以下部分:标识消息类型的头部信息、实际传递的数据内容,以及结束标记。在C#中,可以使用结构体(struct)来定义一个消息类。// 定义消息类型,例如:文本消息、图片消息、在线状态更新等。

weixin_33773084的博客 1012

C#多线程编程---一个简单的聊天程序(Client)

接着上一篇,下面给出客户端的代码。            (1)Form1.cs[设计]界面 (2)Form1.cs[代码]using System;using System.Drawing;using System.Collections;using System.ComponentModel;using System.Windows

JobsMeng的专栏 1472

C#语言使用Socket 实现简易聊天室功能,有源码并且可以直接运行

C# 使用socket实现简易聊天室功能

weixin_45943609的博客 1421
上一篇: 双击自动滚屏
下一篇: 分页
thx_bj
博客等级 码龄21年 5粉丝 33原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值