基于TCP(面向连接)的Socket编程

一、客户端:

1、打开一个套接字(Socket);

2、发起连接请求(connect);

3、如果连接成功,则进行数据交换(read、write、send、recv);

4、数据交换完成,关闭连接(shutdown、close);

二、服务器端:

1、打开一个套接字(Socket);

2、将套接字绑定到服务器地址上(bind);

3、指定套接字为服务器套接字(listen),做好连接请求准备;

4、等待连接请求(connect);

5、如果连接请求到,则连接建立,进行数据交换(read、write、send、recv);

6、数据交换完成,关闭连接(shutdown、close);

基于UDP(面向无连接)的Socket编程

一、客户端\服务器端:

1、打开一个套接字(Socket);

2、将套接字绑定到指定的服务器地址和端口上(bind);

3、进行数据交换(read、write、send、recv);

4、数据交换完成,关闭连接(shutdown、close);

三、MFC对Socket的支持:

1、创建CAsyncSocket对象;

2、发送接收数据报(SendTo、RecvFrom);

3、连接服务器(Connect);

4、接收连接(Listen);

5、发送和接收流式数据(Send、Receive);

6、关闭套接字(Close);

7、差错处理(GetLastError)。

四、实例:网络聊天工具

客户端:

1、。。。。

2、利用类向导重载CAsyncSocket类,生成新的MySocket类。。

3、利用类向导重载CAsyncSocket的OnReceive(int nErrorCode)和OnSend(int nErrorCode)、OnConnect(int nErrorCode)函数。

void MySocket::OnReceive(int nErrorCode)

{

// TODO: Add your specialized code here and/or call the base class

//获取对话框指针

CTestApp*pApp=(CTestApp*)AfxGetApp();

CTestDlg*pDlg=(CTestDlg*)pApp->m_pMainWnd;

//往编辑框中插入消息

char *pbuf=new char[4096];

int ibufsize=4096;

int ircvd;

CString strrecvd;

ircvd=Receive(pbuf,ibufsize);

if(ircvd==SOCKET_ERROR)

{

pDlg->MessageBox("SOCKET_ERROR");

}

else

{

pbuf[ircvd]=NULL;

pDlg->m_recmsg+="服务器:";

pDlg->m_recmsg+=pbuf;

pDlg->m_recmsg+="\r\n";

pDlg->RefreshScreen();

}

delete pbuf;

CAsyncSocket::OnReceive(nErrorCode);

}

void MySocket::OnSend(int nErrorCode)

{

// TODO: Add your specialized code here and/or call the base class

CAsyncSocket::OnSend(nErrorCode);

}

void MySocket::OnConnect(int nErrorCode)

{

// TODO: Add your specialized code here and/or call the base class

CTestApp*pApp=(CTestApp*)AfxGetApp();

CTestDlg*pDlg=(CTestDlg*)pApp->m_pMainWnd;

int iResult=nErrorCode;

CString buffer;

int namelen;

if(iResult!=0)

{

buffer.Format("连接服务器失败。\r\n");

pDlg->m_recmsg+=buffer;

}

else

{

namelen=sizeof(sockaddr_in);

buffer.Format("成功连接到服务器 %s:%d.\r\n",pDlg->m_ipstr,pDlg->m_port);

pDlg->m_recmsg+=buffer;

pDlg->GetDlgItem(IDC_SEND)->EnableWindow(TRUE);

pDlg->GetDlgItem(IDOK)->EnableWindow(TRUE);

}

pDlg->RefreshScreen();

CAsyncSocket::OnConnect(nErrorCode);

}

4、在C*Dlg类中

头文件中:

#include "MySocket.h"

MySocket m_socket;

CString m_ipstr;

.CPP文件中:

void CTestDlg::OnSend()

{

// TODO: Add your control notification handler code here

int ilen;

int isent;

UpdateData(TRUE);

if(m_msg!="")

{

ilen=m_msg.GetLength ();

isent=m_socket.Send(LPCTSTR(m_msg),ilen);

if(isent==SOCKET_ERROR)

{

MessageBox("连接失败,请重试!");

//     connect=false;

}

else

{

m_recmsg+="客户机:"+m_msg;

m_recmsg+="\r\n";

UpdateData(FALSE);

}

}

}

void CTestDlg::RefreshScreen()

{

UpdateData(false);

}

void CTestDlg::OnConnect()

{

if (!AfxSocketInit())

{

AfxMessageBox("IDP_SOCKETS_INIT_FAILED");

return ;

}

GetDlgItemText(IDC_IPADDRESS1,m_ipstr);

m_socket.m_hSocket=INVALID_SOCKET;

UpdateData(true);

BOOL flag=m_socket.Create();

if(!flag)

{

AfxMessageBox("SOCKET ERROR");

return;

}

m_socket.Connect(m_ipstr,m_port);

}

void CTestDlg::OnOK()

{

// TODO: Add extra validation here

m_socket.Close();

CDialog::OnOK();

}

服务器端:

1、。。。。

2、利用类向导重载CAsyncSocket类,生成新的MySocket类。。

3、利用类向导重载CAsyncSocket的OnReceive(int nErrorCode)和OnSend(int nErrorCode)函数。

void MySocket::OnReceive(int nErrorCode)

{

// TODO: Add your specialized code here and/or call the base class

CTestApp*pApp=(CTestApp*)AfxGetApp();

CTestDlg*pDlg=(CTestDlg*)pApp->m_pMainWnd;

//往列表框中插入消息

char *pbuf=new char[4096];

int ibufsize=4096;

int ircvd;

CString strrecvd;

ircvd=Receive(pbuf,ibufsize);

if(ircvd==SOCKET_ERROR)

{

pDlg->MessageBox("SOCKET_ERROR");

}

else

{

pbuf[ircvd]=NULL;

pDlg->m_msg+="客户机:";

pDlg->m_msg+=pbuf;

pDlg->m_msg+="\r\n";

pDlg->RefreshScreen();

}

delete pbuf;

CAsyncSocket::OnReceive(nErrorCode);

}

void MySocket::OnSend(int nErrorCode)

{

// TODO: Add your specialized code here and/or call the base class

CAsyncSocket::OnSend(nErrorCode);

}

4、新建MyServerSocket类,并添加MySocket * m_socket;即接收请求后的套接字指针。

MySocket * m_socket;

void CMyServerSocket::OnAccept(int nErrorCode)

{

// TODO: Add your specialized code here and/or call the base class

CTestApp*pApp=(CTestApp*)AfxGetApp();

CTestDlg*pDlg=(CTestDlg*)pApp->m_pMainWnd;

//显示连接消息

pDlg->m_msg="客户机连接到服务器";

pDlg->m_msg+="\r\n";

pDlg->RefreshScreen();

pDlg->GetDlgItem(IDC_SEND)->EnableWindow(TRUE);

pDlg->GetDlgItem(IDOK)->EnableWindow(TRUE);

MySocket* psocket=new MySocket();

if(Accept(*psocket))

{

psocket->AsyncSelect(FD_READ);

m_socket=psocket;

}

else

{

delete psocket;

}

CAsyncSocket::OnAccept(nErrorCode);

}

5、C*Dlg类中

void CTestDlg::RefreshScreen()

{

UpdateData(false);

}

void CTestDlg::OnListen() //创建服务器

{

// TODO: Add your control notification handler code here

UpdateData(true);

if (!AfxSocketInit())

{

AfxMessageBox("IDP_SOCKETS_INIT_FAILED");

return ;

}

BOOL flag=m_serversocket.Create(m_port);

if(!flag)

{

AfxMessageBox("SOCKET ERROR");

return;

}

flag=m_serversocket.Listen(1);

if(!flag)

{

AfxMessageBox("SOCKET ERROR");

return;

}

SetDlgItemText(IDC_LISTEN,"正在监听");

}

void CTestDlg::OnSend()

{

// TODO: Add your control notification handler code here

int ilen;

int isent;

UpdateData(TRUE);

if(m_sendmsg!="")

{

ilen=m_sendmsg.GetLength ();

isent=m_serversocket.m_socket->Send(LPCTSTR(m_sendmsg),ilen);

if(isent==SOCKET_ERROR)

{

MessageBox("连接失败,请重试!");

}

else

{

m_msg+="服务器:"+m_sendmsg;

m_msg+="\r\n";

UpdateData(FALSE);

}

}

}

void CTestDlg::OnOK()

{

// TODO: Add extra validation here

m_sendmsg="服务器退出";

UpdateData(false);

OnSend();

m_serversocket.Close();

CDialog::OnOK();

}

基于TCP(面向连接)的Socket编程的更多相关文章

  1. 基于TCP/UDP的socket编程

    基于TCP(面向连接)的socket编程服务器端顺序: 1. 创建套接字(socket) 2. 将套接字绑定到一个本地地址和端口上(bind) 3. 将套接字设为监听模式,准备接收客户请求(liste ...

  2. 网络编程——基于TCP协议的Socket编程,基于UDP协议的Socket编程

    Socket编程 目前较为流行的网络编程模型是客户机/服务器通信模式 客户进程向服务器进程发出要求某种服务的请求,服务器进程响应该请求.如图所示,通常,一个服务器进程会同时为多个客户端进程服务,图中服 ...

  3. Java:基于TCP协议网络socket编程(实现C/S通信)

    目录 一.前言:TCP原理简介 二.Socket编程通信 三.TCP服务器端(具体代码) 四.TCP客户端(具体代码) 五.通信效果演示 六."创意"机器人:价值一个亿的AI核心代 ...

  4. 基于TCP协议的socket编程

    什么是socket Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口.在设计模式中,Socket其实就是一个门面模式,它把复杂的TCP/IP协议族隐藏在Socket接口后面, ...

  5. C语言小项目-基于TCP协议和SOCKET编程的网络通信系统

    1.1 功能结构图   网络通信系统一共由4个模块组成,分别是点对点客户端.点对点服务端.服务器中转服务端.服务器中转客户端.这4个模块是成对使用的,点对点客户端和点对点服务端一起使用,服务器中转服务 ...

  6. 基于TCP协议之socket编程

    #服务端 #导入一个socket模块 import socket #想象成买手机打电话:socket.SOCK_STREAM 表示建立tcp连接 ,udp连接socket.SOCK_DGRAM #买了 ...

  7. Java修炼——基于TCP协议的Socket编程_双向通信_实现模拟用户登录

    首先我们需要客户端和服务器端. 服务器端需要:1.创建ServerSocket对象.2.监听客户端的请求数据.3.获取输入流(对象流)即用户在客户端所发过来的信息.                  ...

  8. 基于TCP 协议的socket 简单通信

    DNS 服务器:域名解析 socket 套接字 : ​ socket 是处于应用层与传输层之间的抽象层,也是一组操作起来非常简单的接口(接受数据),此接口接受数据之后,交由操作系统 为什么存在 soc ...

  9. (4)socket的基础使用(基于TCP协议的并发编程)

    需要实现并发需要依靠socketserver 模块 socketserver模块下有几个功能 def __init__(self, request, client_address, server): ...

随机推荐

  1. Dubbo管控台安装(zookeeper单机版)

    1. zookeeper安装(单机版):http://www.cnblogs.com/wangfajun/p/5251159.html  √ 注意:我这里的dubbo-admin.war是2.5.3版 ...

  2. js验证登录注册

    js验证登录注册的优势,在前台直接验证,不需要在后台读取返回数据验证,减轻服务器压力. 登陆验证得必要性,拦截恶意脚本的登录注册攻击.哈哈,当然有些高手是可以直接跳过js验证的. 所以还是后台验证,并 ...

  3. 【1】【leetcode-127】单词接龙word-ladder

    (不会,经典广度优先搜索) 给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度.转换需遵循如下规则: 每次转换只能改 ...

  4. 常用Java数据库连接池

    概述 在这里所谓的数据库连接是指通过网络协议与数据库服务之间建立的TCP连接.通常,与数据库服务进行通信的网络协议无需由应用程序本身实现,原因有三: 实现复杂度大,需要充分理解和掌握相应的通信协议. ...

  5. tomcat优化之安装并配置apr库

    在谈到tomcat优化时,必然要说到apr库,这个库是C语言实现的,tomcat通过JNI方式使用该库可以大大提高性能. tomcat在使用apr时需要安装apr,apr-util和tomcat-na ...

  6. jsp查询修改

    也是只帖代码....不讲解. 1.search.jsp <%@ page language="java" import="java.util.*" pag ...

  7. FormatMessage

    FormatMessage 获取GetLastError 函数返回的错误代码对应的字符串描述. #include <Windows.h>#include <tchar.h> V ...

  8. 使用 Topshelf 结合 Quartz.NET 创建 Windows 服务

    Ø  前言 之前一篇文章已经介绍了,如何使用 Topshelf 创建 Windows 服务.当时提到还缺少一个任务调度框架,就是 Quartz.NET.而本文就展开对 Quartz.NET 的研究,以 ...

  9. IDApython教程(四)

    前三部分已经验证了用IDAPython能够让工作变的更简单,这一部分让我们看看逆向工程师如何使用IDAPython的颜色和强大的脚本特性. 分析者经常需要面对越来越复杂的代码,而且有时候无法轻易看出动 ...

  10. Nginx正反向代理、负载均衡等功能实现配置

    版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[+]   系统环境: VirtualBox Manager Centos6.4 nginx1.10.0 IP对应的机器名: IP ...