实验二网络基础编程实验_第1页
实验二网络基础编程实验_第2页
实验二网络基础编程实验_第3页
实验二网络基础编程实验_第4页
实验二网络基础编程实验_第5页
已阅读5页,还剩18页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、计算机网络实验报告信息安全2015年 4 月 1日湖南大学计算机网络实验报告二实验二网络基础编程实验、实验目的通过本实验,学习采用 Socket (套接字)设计简单的网络数据收发程序,理解应用数据 包是如何通过传输层进行传送的。二、实验内容2.1、编写TCP进行数据发送的简单程序(java)TCP Client. j a vTaC P Server.java2.2、编写UDP进行数据发送的简单程序(java)15 / 22UDP Server.javaUDP Client.java2.3多线程线程池对比TCP EchoClient.javaTCP EchoServer.javaTCP Echo

2、ServerThread.javaTCP EchoServerPool.java2.4写一个简单的chat程序,编程语言不限。三、实验程序(1) TCP客户端 TcpClient.javaimport java.io.*;import java .n et.*;p ublic class Tcp Clie ntp ublic static void main( Stri ng argv) throws Excep tio n Stri ng senten ce;/定义客户消息Stri ng modifiedSe nte nee;/定义服务器消息获取本机端口In etAddress addres

3、s = In etAddress.getLocalHost();/BufferedReader inFro mUser = new BufferedReader( new Inpu tStreamReader(Syst em.i n); /创建客户输入流TCP连接。add/创建一个Scoket实例:构造函数向指定的远程主机和端口建立一个 ress.getHostName() 为本机IP地址;6789为TCP服务器端口客户套接字Socket clie ntSocket = new Socket(address.getHostName(),6789); /通过套接字的输入输出流(I/O strea

4、ms)进行通信DataOut pu tStream outToServer = new DataOut pu tStream( clie ntSocket.getOut put Stream(); /创建客户端到服务器的输出流BufferedReader inF romServer = new BufferedReader( new Inpu tStreamReader(cli en tSocket.getI np utStream(); /创建服务端输入流se ntence = inF romUser.readLi ne();/客户端读取客户输入消息outToServer.writeByte

5、s(se nten ce+n); /客户端发送消息到服务器端modifiedSe nte nee =in FromServer.readL in e();/客户端接收来自服务器的消息System.out. prin tl n(clie nt receive from TCP server: + modifiedSe nten ce);/客户端显示服务器发送过来的消息clie ntSocket.close(); /客户端关闭套接字(2) TCP服务器端 TcpServer.javaimport java.io.*;import java .n et.*;p ublic class Tep Ser

6、ver p ublic static void main( Stri ng argV) throws Exce pti on Stri ng clie ntSe nte nee;/定义接收的消息Stri ng cap italizedSe nten ce;/定义发送的消息ServerSocket welcomeSocket= new ServerSocket(6789);/创建一个ServerSocket实例,并指定本地端口,侦听该指定端口收到的连接 while(true)Socket conn ecti on Socket = welcomeSocket.acce pt();/调用Serve

7、rSocket的accept()方法以获取下一个客户端连接,基于新建立的 客户端连接,创建一个Socket实例,并由accept()方法返回。BufferedReader inF romClie nt = new BufferedReader( new Inpu tStreamReade r(conn ectio nSocket.getl npu tStream();/创建客户端输入流DataOut pu tStream outToClie nt = new DataOut pu tStream(c onnection Socket.g etOut putStreamO);/创建服务器输出流/

8、使用所返回的Socket实例的InputStream和OutputStream与客户端进行通信。clie ntSe ntence = inF romClie nt.readL in e(); /接收客户发送的信息转换接收到cap italizedSe ntence = clie ntSe nten ce.to Upp erCase()+n; /的信息,小写变大写输出给客户(3)outToClie nt.writeBytes(TC P accep t +ca pi talizedSe nten ce);/UDP通 信服务器端 UDP Server.java import java.io.*;im

9、port java .n et.*;p ublic class UDP Server p ublic static void main( Stri ng argV) throws Exce pti on 构造数据包套接DatagramSocket serverSocket = new DatagramSocket (9876); / 字并将其绑定到主机上的端口9876服务器从客户端接收到的信息服务器发送给客户端的信息byte receiveData = new byte1024; /byte sen dData = new byte1024; /while(true)DatagramPacke

10、t receivePacket = new DatagramPacket(receiveData,receiveD ata.length); / 创建从客户端数据包serverSocket.receive(receivePacket); / 服务器从客户端接收数据包获取客户端的 IP 地将接收的信息转为String sentence = new String(receivePacket.getData(); / 服务器接打开 数据包得到消息InetAddress IPAddress = receivePacket.getAddress();/int port = receivePacket.g

11、etPort();/获取客户端端口String capitalizedSentence = sentence.toUpperCase();/大写转换后的消息sendData = capitalizedSentence.getBytes(); / 服务器发送给客户端的数据包,将转换后的消息打包DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.lengt h,IPAddress,port);服务器发送数据包给客户端serverSocket.send(sendPacket);/(4) UDP通信客户端 UDPClient

12、.javaimport java.io.*;import .*;public class UDPClientpublic static void main(String argv) throws Exception byte receiveData = new byte1024; /客户端接收的消息byte sendData = new byte1024;/客户端发送的消息BufferedReader inFromReader = new BufferedReader( new InputStreamReader(Sy stem.in);/ 客户输入流DatagramSocket client

13、Socket = new DatagramSocket (); /客户端数据包套接字InetAddress IPAddress = InetAddress.getLocalHost(); /获取本机 IP 地址String sentence = inFromReader.readLine(); /客户端读取用户所输入的消息sendData = sentence.getBytes(); /复制到要发送的消息/ 客户端发送的数据包,这里将客户端要发送的消息,客户端的IP 地址,端口打包DatagramPacket sendPacket = new DatagramPacket(sendData,s

14、endData.length,IPAddress,9876);clientSocket.send(sendPacket);/客户端套接字发送数据包/ 客户端接收的数据包,数据包包含从服务器接收的消息,消息长度DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData. length);clientSocket.receive(receivePacket); /客户端接收数据包将接收的String modifiedSentence = new String(receivePacket.getData(); /

15、数据包解开System.out.println(client receive from UDP server: + modifiedSentence + from from the client!); /客户端显示数据包里的消息clientSocket.close(); /关闭套接字通过TCP协议与回馈服务器(echo server )进行通信的客户端TCPEchoClient.javaimport java.i o.I OExce pti on;import java.i o.Inpu tStream;import java.io.Out putStream;import java .n e

16、t.ServerSocket;import java .n et.Socket;import java .n et.SocketAddress;p ublic class TCP EchoServerprivate static final int BUFSIZE = 32;p ublic static void main( Stri ng args) throws IOExce pti onif (args.le ngth != 1)/获取启动服务的端口throw new IllegalArgume ntExce pti on (” Parameter(s): );int serv Port

17、 = In teger. parse In t(args0);/分配一个端口用于启动 server端ServerSocket servSock = new ServerSocket(serv Port);int recvMsgSize;byte receiveBuf = new byteBUFSIZE;while (true)Socket cl ntSock = servSock.acce pt(); /接收客户端的主动连接SocketAddress clie ntAddress = cin tSock.getRemoteSocketAddress(); System.out .prin tl

18、 n(Ha ndli ng clie nt at + clie ntAddress);Inpu tStream in = cIn tSock.getI npu tStream();Outpu tStream out = cin tSock.getOut pu tStream(); while (recvMsgSize = in. read(receiveBuf) != -1) out.write(receiveBuf, 0, recvMsgSize);cin tSock.close();为前面的客户端程序实现回馈服务器TCPEchoServer.javaimport java.i o.I OE

19、xce pti on;import java.i o.Inpu tStream;import java.io.Out putStream;import java .n et.Socket;import java .n et.SocketExce pti on;public class TCP EchoClie ntp ublic static void main( Stri ng args) throws IOExce pti on传入的数据在23之间,0:if (args.le ngth 3) /地址1 :传输字符throw new IllegalArgume ntExce ptio n(”

20、 Parameter(s): );地址或主机名称String server = args0; /ipbyte data = args1.getBytes();int serv Port = (args .len gth = 3) ? In teger. parse In t(args2) : 7;默认端口为7Socket socket = new Socket(server, servPort);System.out. printin (C onn ected to server.se nding echo stri ng);Inpu tStream in = socket.get Inpu

21、tStream();Outpu tStream out = socket.getOut pu tStream();out.write(data);int totalBytesRcvd = 0;int bytesRcvd;while (totalBytesRcvd data.le ngth) if (bytesRcvd = in. read(data, totalBytesRcvd,data .len gth - totalB ytesRcvd) = -1)throw new SocketExce pti on (C onnection closed p rematurely); totalBy

22、tesRcvd += bytesRcvd;System.out. printin (Received: + new Strin g(data);socket.close();(7) 客户一线程/二、每个客户端请求都新启一个线程的Tcp服务端:import java.io.lOException;import java .n et.ServerSocket;import java .n et.Socket;import java.util.logg in g.Logger;p ublic class TCP EchoServerThread p ublic static void main( S

23、tri ng args) throws Exce pti on /IOExce ptio nServerSocket servSock = new ServerSocket(5500);Logger logger = Logger.getLogger(” practical);while (true) Socket cin tSock = servSock.acce pt(); / Block wait ing for conn ectioThread thread = new Thread( new EchoP rotocol(cl ntSock, logger); thread.start

24、();logger.i nfo(Created and started Thread + thread.getName();(8) 线程池/三、固定线程数的 Tcp服务端import java.i o.I OExce pti on;import java .n et.ServerSocket;import java .n et.Socket;import java.util.logg in g.Level;import java.util.logg in g.Logger;public class TCP EchoServerPool p ublic static void main( Str

25、i ng args) throws IOExce pti on int thread PoolSize = 3; / Fixed Thread PoolSizefinal ServerSocket servSock = new ServerSocket(5500);final Logger logger = Logger.getLogger( practical);for (int i = 0; i Loadlco n(IDR_MAINFRAME);void CNetChatServerDlg:DoDataExcha nge(CDataExcha nge* p DX) /AFX_DATA_MA

26、 P(CNetChatServerDlg) DDX_Co ntrol( pDX, IDC_ PORT, m_portCtrl);DDX_Co ntrol( pDX, IDC_EDIT_MSG, m_editMsg);DDX_Co ntrol( pDX, IDC_SHOW_MSG, m_showMsg); DDX_Text( pDX, IDC_ PORT, m_serverPort);BEGIN_MESSAGE_MA P(CNetChatServerDlg, CDialog)/AFX_MSG_MA P(CNetChatServerDlg)ON_MESSAGE(WM_SOCKET, On Sock

27、et) ON_WM_SYSCOMMAND()ON_WM_P AINT()ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_START_SERVER, OnStartServer) ON_BN_CLICKED(IDC_SEND_MSG, OnSendMsg) ON_EN_MAXTEXT(IDC_SHOW_MSG, OnMaxtextShowMsg) /AFX_MSG_MAPEND_MESSAGE_MAP()BOOL CNetChatServerDlg:OnInitDialog()CDialog:OnInitDialog();SetIcon(m_hIcon, TRUE

28、);/ Set big iconSetIcon(m_hIcon, FALSE); / Set small icon / TODO: Add extra initialization hereCtrlState(FALSE); m_portCtrl.SetLimitText(5);/65535 return TRUE; / return TRUE unless you set the focus to a controlvoid CNetChatServerDlg:OnSysCommand(UINT nID, LPARAM lParam) if(nID & 0xFFF0) = SC_CLOSE

29、& m_serverSocket != INVALID_SOCKET) OnStartServer();CDialog:OnSysCommand(nID, lParam);void CNetChatServerDlg:OnPaint() if (IsIconic()CPaintDC dc(this); / device context for paintingSendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = Get

30、SystemMetrics(SM_CYICON);CRect rect;GetClientRect(&rect);int x = (rect.Width() - cxIcon + 1) / 2;int y = (rect.Height() - cyIcon + 1) / 2; dc.DrawIcon(x, y, m_hIcon); elseCDialog:OnPaint();HCURSOR CNetChatServerDlg:OnQueryDragIcon() return (HCURSOR) m_hIcon;BOOL CNetChatServerDlg:PreTranslateMessage

31、(MSG* pMsg) return CDialog:PreTranslateMessage(pMsg);void CNetChatServerDlg:CtrlState(BOOL state) m_editMsg.EnableWindow(state); GetDlgItem(IDC_SEND_MSG)-EnableWindow(state);void CNetChatServerDlg:O nStartServer() CStri ng msg;m_showMsg.GetWi ndowText(msg);if(m_serverSocket != INVALID_SOCKET)/ 已经启动服

32、务器,则停止服务器if(m_clie ntSocket != INVALID_SOCKET):closesocket(m_clie ntSocket);:closesocket(m_serverSocket);:WSAClea nup();CtrlState(FALSE);GetDlgltem(IDC_START_SERVER)-SetWindowText(” 启动服务器”);m_p ortCtrl.E nableWi ndow(TRUE); m_serverSocket = INVALID_SOCKET; m_clie ntSocket = INVALID_SOCKET; msg += rn

33、服务器已停止!;else/启动服务器Up dateData(TRUE);if(m_serverPort 65535)AfxMessageBox(服务器端口溢出!请重新设定!);return;WSADATA data;if(:WSAStartu p(MAKEWORD(2, 2), &data)AfxMessageBox(启动套接字失败!);return;sockaddr_ in addr;addr.sin_family = AF_INET;addr.s in_port = hton s(m_server Port);addr.sin_addr.S_u n. S_addr = INADDR_ANY

34、; m_serverSocket = :socket(AF_INET,SOCK_STREAM,0); if(INVALID_SOCKET = m_serverSocket |:bi nd(m_serverSocket, (sockaddr*)&addr, sizeof(addr) = SOCKET_ERROR II:liste n( m_serverSocket, 1) = SOCKET_ERROR |:WSAAsy ncSelect(m_serverSocket, this-m_hWnd, WM_SOCKET, FD_ACCE PT |FD_READ|FD_CLOSE) = SOCKET_E

35、RROR)AfxMessageBox(创建服务器失败r);:WSAClea nup();m_serverSocket = INVALID_SOCKET;return;m_p ortCtrl.E nableWi ndow(FALSE);GetDlgItem(IDC_START_SERVER)-SetWindowText( 停止服务器 ); msg += rn 服务器已启动 ;m_showMsg.SetWindowText(msg); m_showMsg.LineScroll(m_showMsg.GetLineCount(); void CNetChatServerDlg:OnSendMsg()

36、if(m_clientSocket != INVALID_SOCKET) char send500 = 0; m_editMsg.GetWindowText(send, sizeof(send) - 1); int strlength = strlen(send); if(strlength LoadIcon(IDR_MAINFRAME); m_clientSocket = INVALID_SOCKET;void CNetChatClientDlg:DoDataExchange(CDataExchange* pDX) CDialog:DoDataExchange(pDX);/AFX_DATA_

37、MAP(CNetChatClientDlg)DDX_Control(pDX, IDC_SHOW_MSG, m_showMsg); DDX_Control(pDX, IDC_EDIT_MSG, m_editMsg); DDX_Control(pDX, IDC_IPADDR, m_ipAddr); DDX_Control(pDX, IDC_PORT, m_portCtrl);DDX_Text(pDX, IDC_PORT, m_port); /AFX_DATA_MAPBEGIN_MESSAGE_MAP(CNetChatClientDlg, CDialog) /AFX_MSG_MAP(CNetChat

38、ClientDlg) ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_BN_CLICKED(IDC_SEND, OnSend) ON_BN_CLICKED(IDC_CONNECT, OnConnect) ON_WM_TIMER()ON_MESSAGE(WM_SOCKET,OnSocket) /AFX_MSG_MAPEND_MESSAGE_MAP()BOOL CNetChatClientDlg:OnInitDialog()CDialog:OnInitDialog();SetIcon(m_hIcon, TRUE);/ Set big i

39、conSetIcon(m_hIcon, FALSE); / Set small icon m_ipAddr.SetWindowText(192.168.1.104);CtrlState(TRUE);return TRUE; / return TRUE unless you set the focus to a control void CNetChatClientDlg:OnSysCommand(UINT nID, LPARAM lParam)if (nID & 0xFFF0) = SC_CLOSE & m_clientSocket != INVALID_SOCKET) OnConnect()

40、;CDialog:O nSysComma nd( nID, I Param);void CNetChatClie ntDlg:O nP ai nt()if (IsIco nic()CPaintDC dc(this); / device con text for paintingSen dMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);int cxIcon = GetSystemMetrics(SM_CXICON);int cyIco n = GetSystemMetrics(SM_CYICON);CRect rect;GetCli

41、e ntRect(&rect);int x = (rect.Width() - cxIcon + 1) / 2;int y = (rect.Height() - cyIco n + 1) / 2;dc.DrawIc on(x, y, m_hIc on);elseCDialog:O nP ai nt();HCURSOR CNetChatClie ntDlg:O nQueryDragIco n()return (HCURSOR) m_hIco n;BOOL CNetChatClie ntDIg: PreTra nslateMessage(MSG* pMsg) return CDialog: Pre

42、Tra nslateMessage( pM sg);void CNetChatClie ntDlg:O nSen d() if(m_clie ntSocket != INVALID_SOCKET)char sen d500 = 0;m_editMsg.GetWi ndowText(se nd, sizeof(se nd) - 1);int strle ngth = strle n(sen d); if(strle ngth EnableWindow(!state); m_editMsg.EnableWindow(!state);已经启动服务器,则停止服务器 void CNetChatClien

43、tDlg:OnConnect() CString msg; m_showMsg.GetWindowText(msg); if(m_clientSocket != INVALID_SOCKET)/ :closesocket(m_clientSocket); :WSACleanup(); CtrlState(TRUE); m_clientSocket = INVALID_SOCKET; msg += rn 已断开 !; else/ 启动服务器 UpdateData(TRUE); if(m_port 65535) AfxMessageBox( 端口溢出 ! 请重新设定 !); return;WSAD

44、ATA data;if(:WSAStartup(MAKEWORD(2, 2), &data) AfxMessageBox( 启动套接字失败 !); return; sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(m_port); m_ipAddr.GetAddress(addr.sin_addr.S_un.S_un_b.s_b1, addr.sin_addr.S_un.S_un_b.s_b2,addr.sin_addr.S_un.S_un_b.s_b3, addr.sin_addr.S_un.S_un_b.s

45、_b4); m_clientSocket = :socket(AF_INET, SOCK_STREAM, 0); if(INVALID_SOCKET = m_clientSocket |:WSAAsyncSelect(m_clientSocket, this-m_hWnd, WM_SOCKET, FD_CONNEC T|FD_READ|FD_CLOSE) = SOCKET_ERROR)AfxMessageBox( 连接失败 !); :WSACleanup();m_clientSocket = INVALID_SOCKET; return;:connect(m_clientSocket, (sockaddr*)&addr, sizeof(addr);SetTimer(1,4000, NULL);msg +

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论