C 簡單聊天室雛形

2021-07-15 20:03:23 字數 2016 閱讀 6244

程式使用的控制台的黑視窗模擬程式,第一次涉及網路程式設計,寫出來方便以後查閱,**很簡單

首先是伺服器端的**:

public

class servercontrol

public

void

start()

}

主程式:

static

void main(string args)

下面是客戶端**:

public

class clientcontrol

public

void

connect(string ip, int port)

}

客戶端的呼叫**:

static

void main(string args)

private

void

accept()

因為要在伺服器啟動就要去檢測有沒有連線到伺服器的ip,所以需要在start方法中開闢乙個新的執行緒來呼叫accept方法

thread threadaccept =

newthread(accept); //接收乙個委託方法

threadaccept.isbackground =

true; //設定為後台執行緒

threadaccept.start();

下一步就是客戶端要往伺服器傳送訊息

客戶端的clientcontrol類**:

public

void

send(string msg)

客戶端主程式呼叫**:

console.writeline("請輸入要傳送的內容, 輸入exit退出:");

string msg = console.readline();

while (msg != "exit")

下一步就是要在伺服器接收客戶端的輸入內容

private

void

receive(object obj)

catch

這個方法執行同樣會掛起執行緒,所以要開闢乙個新的執行緒,因為這是接收客戶端的訊息,所以這個新執行緒要寫在剛才寫的accept方法裡面

thread threadreceive =

newthread(receive);

threadreceive.isbackground =

true;

threadreceive.start(client);

附加:

剛才不是寫了乙個伺服器接收到訊息,會給客戶端返回乙個相同的訊息,所以還要在客戶端接收伺服器的訊息,方法和在伺服器端接收大同小異

private

void

receive()

catch

}

以為一連上就要去檢測伺服器有沒有訊息,所以開闢乙個執行緒 寫在客戶端的 connect方法中

thread threadreceive =

newthread(receive);

threadreceive.isbackground =

true;

threadreceive.start();

好了 ,乙個最簡單的聊天室就算寫完了

想多人登陸 就在vs中找到客戶端的debug資料夾 找到exe檔案執行

簡單聊天室

include include include include include include include include include include pthread t thread 2 void send msg void ip msg if connect sockfd,struct ...

Linux UDP簡單聊天室

伺服器端 include include include include include include include include int sockfd 0 建立結構體用來存放客戶端資訊 typedef struct node node t node t link head node t h ...

go 簡單聊天室

package main import fmt net strings time 建立使用者結構體型別 type cline struct var onlinemap map string cline 建立全域性 channel 傳遞使用者訊息 var message make chan strin...