原文地址: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