package main
import (
"fmt"
"log"
"net"
)
var ConnMap map[string]*net.TCPConn
func boradcastMessageString(message string) {
b := []byte(message)
for _, conn := range ConnMap {
conn.Write(b)
}
}
func boradcastMessage(message []byte) {
for _, conn := range ConnMap {
conn.Write(message)
}
}
//检查错误
func checkError(err error) int {
if err != nil {
if err.Error() == "EOF" {
//fmt.Println("用户退出了")
return 0
}
log.Fatal("an error!", err.Error())
return -1
}
return 1
}
//处理客户端消息
func doServerStuff(pConn *net.TCPConn) {
var szIp = pConn.RemoteAddr().String()
ConnMap[szIp] = pConn
defer func() {
fmt.Println("断开连接 :" + szIp)
pConn.Close()
delete(ConnMap, szIp)
}()
nCount := 0
for {
szBuf := make([]byte, 512)
_, err := pConn.Read(szBuf) //读取客户机发的消息
flag := checkError(err)
if flag == 0 {
break
}
nCount++
boradcastMessage(szBuf)
fmt.Println(nCount, string(szBuf)) //打印出来
}
}
func startServer() {
fmt.Println("服务器启动")
ConnMap = make(map[string]*net.TCPConn)
var tcpAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:8083")
fmt.Println("解析后的IP地址", tcpAddr)
var pListener, _ = net.ListenTCP("tcp", tcpAddr)
fmt.Println(pListener)
nCount := 0
for {
fmt.Println("等待连接中")
var pConn, _ = pListener.AcceptTCP()
nCount++
fmt.Println("有连接的内容", nCount, pConn.RemoteAddr().String())
go doServerStuff(pConn)
}
fmt.Println("启动完毕")
}
func main() {
fmt.Println("GO启动")
startServer()
fmt.Println("GO结束")
}
用go语言做一个普通的聊天服务器
unit Unit2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Win.ScktComp;
type
TForm2 = class(TForm)
ClientSocket1: TClientSocket;
Button1: TButton;
Edit1: TEdit;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
procedure TForm2.Button1Click(Sender: TObject);
begin
ClientSocket1.Socket.SendText(AnsiString(Edit1.Text));
end;
procedure TForm2.ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket);
begin
Memo1.Lines.Add(Socket.ReceiveText);
end;
end.