如何用C语言编写一个简单的聊天室程序

如何用C语言编写一个简单的聊天室程序,第1张

这样:

#include <stdlib.h>

#include <stdio.h>

#include <errno.h>

#include <string.h>

#include <unistd.h>

#include <netdb.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <sys/types.h>

#include <arpa/inet.h>

#include <pthread.h>

#define MAXLINE 100

void *threadsend(void *vargp)

void *threadrecv(void *vargp)

int main()

{

int *clientfdp

clientfdp = (int *)malloc(sizeof(int))

*clientfdp = socket(AF_INET,SOCK_STREAM,0)

struct sockaddr_in serveraddr

struct hostent *hp

bzero((char *)&serveraddr,sizeof(serveraddr))

serveraddr.sin_family = AF_INET

serveraddr.sin_port = htons(15636)

serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1")

if(connect(*clientfdp,(struct sockaddr *)&serveraddr,sizeof(serveraddr)) <0){

      printf("connect error\n")

      exit(1)

}

pthread_t tid1,tid2

printf("connected\n")

while(1){

pthread_create(&tid1,NULL,threadsend,clientfdp)

pthread_create(&tid2,NULL,threadrecv,clientfdp)

}

return EXIT_SUCCESS

}

void *threadsend(void * vargp)

{

//pthread_t tid2

int connfd = *((int *)vargp)

int idata

char temp[100]

while(1){

//printf("me: \n ")

fgets(temp,100,stdin)

send(connfd,temp,100,0)

printf("   友链       client send OK\n")

}

printf("client send\n")

return NULL

}

void *threadrecv(void *vargp)

{

char temp[100]

int connfd = *((int *)vargp)

while(1){

int idata = 0

idata = recv(connfd,temp,100,0)

if(idata >0){

printf("server :\n%s\n",temp)

}

}

return NULL

}

扩展资料:

注意事项

linux下编译多线程代码时,shell提示找键告蠢不到 pthread_create函数,原因是 pthread.h不是linux系统默认加载的库文件,应该使用类似如下gcc命令进行编译稿陪:

gcc echoserver.c -lpthread -o echoserver

只要注意 -lpthread参数就可以了。

  //"开始"大禅按钮事件 

  private void button1_Click(object sender, System.EventArgs e) { 

   //取得预保存的文件名 

   string fileName=textBox3.Text.Trim() 

   //远程主机 

   string hostName=textBox1.Text.Trim() 

   //端口 

   int port=Int32.Parse(textBox2.Text.Trim()) 

   //得到主机信息 

   IPHostEntry ipInfo=Dns.GetHostByName(hostName) 

   //取得滚亏尘IPAddress[] 

   IPAddress[] ipAddr=ipInfo.AddressList 

   //得到ip 

   IPAddress ip=ipAddr[0] 

   //组合出远程终结点 

   IPEndPoint hostEP=new IPEndPoint(ip,port) 

   //创建Socket 实例 

   Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp) 

   try 

   { 

   //尝试连接 

   socket.Connect(hostEP) 

   } 

   catch(Exception se) 

   { 

   MessageBox.Show("连接错误"+se.Message,"提示信息 

   ,MessageBoxButtons.RetryCancel,MessageBoxIcon.Information) 

  } 

  //发送给远程主机的请求内容串 

  string sendStr="GET / HTTP/1.1\r\nHost: " + hostName + 

  "\r\nConnection: Close\r\n\r\n" 

   //创建bytes字节数组以转换发送串 

   byte[] bytesSendStr=new byte[1024] 

   //将发送内容字符串转换成字节byte数组 

   bytesSendStr=Encoding.ASCII.GetBytes(sendStr) 

  try 

  { 

  //向主机发送请求 

  socket.Send(bytesSendStr,bytesSendStr.Length,0) 

  } 

  catch(Exception ce) 

   { 

   MessageBox.Show("发送错误:"+ce.Message,"提示信息 

   ,MessageBoxButtons.RetryCancel,MessageBoxIcon.Information) 

   } 

   //声明接收返回内容的字符串 

   string recvStr="" 

   //声明字节数组,一次接收数据的长度为1024字节 

 空敬  byte[] recvBytes=new byte[1024] 

   //返回实际接收内容的字节数 

   int bytes=0 

  //循环读取,直到接收完所有数据 

  while(true) 

  { 

  bytes=socket.Receive(recvBytes,recvBytes.Length,0) 

  //读取完成后退出循环 

  if(bytes〈=0) 

  break 

  //将读取的字节数转换为字符串 

  recvStr+=Encoding.ASCII.GetString(recvBytes,0,bytes) 

  } 

  //将所读取的字符串转换为字节数组 

  byte[] content=Encoding.ASCII.GetBytes(recvStr) 

   try 

   { 

   //创建文件流对象实例 

   FileStream fs=new FileStream(fileName,FileMode.OpenOrCreate,FileAccess.ReadWrite) 

  //写入文件 

  fs.Write(content,0,content.Length) 

  } 

  catch(Exception fe) 

   { 

   MessageBox.Show("文件创建/写入错误:"+fe.Message,"提示信息",MessageBoxButtons.RetryCancel,MessageBoxIcon.Information) 

   } 

   //禁用Socket 

   socket.Shutdown(SocketShutdown.Both) 

   //关闭Socket 

   socket.Close() 

   } 

   }

   

#include <stdio.h>

#include <winsock2.h>

#define MAX_SIZE 200

void main(void) {

WORD wVersionRequested

WSADATA wsaData

int err

wVersionRequested = MAKEWORD( 1, 1 )

err = WSAStartup( wVersionRequested, &wsaData )

if ( err != 0 ) {

/* Tell the user that we could not find a usable */

/* WinSock DLL. */

return

}

/* Confirm that the WinSock DLL supports 2.2.*/

/* Note that if the DLL supports versions greater*/

/* than 2.2 in addition to 2.2, it will still return */

/* 2.2 in wVersion since that is the version we */

/* requested.*/

if ( LOBYTE( wsaData.wVersion ) != 1 ||

HIBYTE( wsaData.wVersion ) != 1 ) {

/* Tell the user that we could not find a usable */

/* WinSock DLL. */

WSACleanup( )

return

}

SOCKET sockSrv = socket(AF_INET, SOCK_DGRAM, 0)

SOCKADDR_IN addrSrv

addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY)

addrSrv.sin_family = AF_INET

addrSrv.sin_port = htons(6000)

bind(sockSrv, (SOCKADDR *)&addrSrv, sizeof(SOCKADDR))

SOCKADDR addrClient

char recvBuffer[MAX_SIZE]

memset(recvBuffer, 0, sizeof(recvBuffer))

int len = sizeof(SOCKADDR)

recvfrom(sockSrv, recvBuffer, sizeof(recvBuffer), 0, (SOCKADDR *)&addrClient, &len)

printf("%s\n", recvBuffer)

closesocket(sockSrv)

}

#include <stdio.h>

#include <winsock2.h>肆禅

void main(void) {

WORD wVersionRequested

WSADATA wsaData

int err

wVersionRequested = MAKEWORD( 1, 1 )

err = WSAStartup( wVersionRequested, &wsaData )

if ( err != 0 ) {

/指雹斗* Tell the user that we could not find a usable */

/* WinSock DLL. */

return

}

/唯磨* Confirm that the WinSock DLL supports 2.2.*/

/* Note that if the DLL supports versions greater*/

/* than 2.2 in addition to 2.2, it will still return */

/* 2.2 in wVersion since that is the version we */

/* requested.*/

if ( LOBYTE( wsaData.wVersion ) != 1 ||

HIBYTE( wsaData.wVersion ) != 1 ) {

/* Tell the user that we could not find a usable */

/* WinSock DLL. */

WSACleanup( )

return

}

/* The WinSock DLL is acceptable. Proceed. */

SOCKET sockClient = socket(AF_INET, SOCK_DGRAM, 0)

SOCKADDR_IN addrClient

addrClient.sin_addr.S_un.S_addr = inet_addr("127.0.0.1")

addrClient.sin_family = AF_INET

addrClient.sin_port = htons(6000)

sendto(sockClient, "你若此生若只如一瞬", strlen("你若此生若只如一瞬"), 0, (SOCKADDR *)&addrClient, sizeof(SOCKADDR))

closesocket(sockClient)

WSACleanup()

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12544547.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-26
下一篇 2023-05-26

发表评论

登录后才能评论

评论列表(0条)

保存