go语言实现聊天服务器(多人聊天)

原文地址:https://blog.csdn.net/dyd961121/article/details/81252920

用go语言实现一个server作中转群发消息,多个客户端聊天

1)服务器开启,等待来自客户端的连接,把每一个客户端存储在map中

2)客户端连接服务器,给自己取一个别名,存储在服务器

3)服务器群发消息,通知在线的客户端有新的加入

4)客户端发消息,服务器解析协议,群发给每一个客户端

5)客户端下线

server

// server project main.go
package main
 
import (
	"fmt"
	"net"
)
 
//var ConnMap map[string]*net.TCPConn
 
func main() {
	listen_socket, err := net.Listen("tcp", "127.0.0.1:8000")
	if err != nil {
		fmt.Println("sever start error")
	}
 
	defer listen_socket.Close()
	fmt.Println("server is wating ....")
 
	for {
		conn, err := listen_socket.Accept()
		if err != nil {
			fmt.Println("conn fail ...")
		}
		fmt.Println("connect client successed")
 
		var msg string
		for {
			msg = ""
			data := make([]byte, 255)
			msg_read, err := conn.Read(data)
			if msg_read == 0 || err != nil {
				break
			}
 
			msg_read_str := string(data[0:msg_read])
			if msg_read_str == "close" {
				conn.Write([]byte("close"))
				break
			}
			//fmt.Println(string(data[0:msg_read]))
			fmt.Println("client say: ", msg_read_str)
 
			fmt.Printf("say to client: ")
			fmt.Scan(&msg)
			//conn.Write([]byte("hello client\n"))
			//msg_write := []byte(msg)
			conn.Write([]byte(msg))
		}
		fmt.Println("client Close\n")
		conn.Close()
	}
 
}

client

using System;
using System.Net;
using System.Net.Sockets;
using System.Collections;
 
 
public class netClient
{
    public static void Main(string[] args)
    {
        Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        string host = "127.0.0.1";
        int port = 8000;
        _socket.Connect(host, port);
        Console.WriteLine("连接成功");
 
        while (true)
        {
            string buffStr;
            
            Console.WriteLine("对服务器说:");
            buffStr = Console.ReadLine();
            Console.WriteLine("对服务器说:" + buffStr);
 
            byte[] readBuff = System.Text.Encoding.UTF8.GetBytes(buffStr);
         
            try
            {
                _socket.Send(readBuff);
            }
            catch { }
            
 
            int buffCount = _socket.Receive(readBuff);
 
            buffStr = System.Text.Encoding.UTF8.GetString(readBuff, 0, buffCount);
            Console.WriteLine("服务器说:" + buffStr);
 
        }
 
 
    }
 
 
}

程序截图

 

不同语言间的通信: https://blog.csdn.net/dyd961121/article/details/81355147

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值