JavaSocket的API应用

版权声明:本文为博主原创文章,未经博主允许不得转载哦。 https://blog.csdn.net/a464700300/article/details/66975276

Java中的网络支持

针对网络通信的不同层次,Java提供的网络功能有四类

  1. InetAddress:用于标识网络上的硬件资源
  2. URL:统一资源定位符,通过URL可以直接读取或写入网络上的数据
  3. Sockets:使用TCP协议实现网络通信的Socket相关的类
  4. Datagram:使用UDP协议,将数据保存在数据报中,通过网络进行通信

InetAddress的使用

//获取本机的InetAddress实例
InetAddress address = InetAddress.getLocalHost();
System.out.println("本机名:"+address.getHostName());
System.out.println("IP地址:"+address.getHostAddress());

//获取IP地址字节数组的形式
byte[] bytes = address.getAddress();
System.out.println("字节数组IP:"+bytes.toString());
//直接输出InetAddress对象(本机名+IP)
System.out.println(address);

//根据主机名获取InetAddress实例
InetAddress address1=InetAddress.getByName("USER-20170104RF");
//根据IP地址获取InetAddress实例
InetAddress address1=InetAddress.getByName("192.168.0.1");

URL的使用

url由两部分组成,协议名称和资源名称

//创建一个URL实例
URL i = new URL("http://www.baidu.com");
//根据上一个实例创建一个新实例,?后表示参数,#表示锚点
URL url = new URL(i,"/index.html?username=tom#test");

System.out.println("协议:"+url.getProtocol());
System.out.println("主机:"+url.getHost());
System.out.println("端口:"+url.getPort());
System.out.println("文件路径:"+url.getPath());
System.out.println("文件名:"+url.getFile());
System.out.println("相对路径:"+url.getRef());
System.out.println("查询字符串 :"+url.getQuery());

使用URL读取网页内容

通过URL对象的openStream()方法可以得到指定资源的输入流

        //创建一个URL实例
        URL url=new URL("http://www.baidu.com");
        //通过URL的openStream方法获取URL对象所表示的资源的字节输入流
        InputStream is=url.openStream();
        //字节输入流转化为字符输入流
        InputStreamReader isr=new InputStreamReader(is,"utf-8");
        //为字符输入流添加缓冲,提高效率
        BufferedReader br=new BufferedReader(isr);

        //读取数据
        String data=br.readLine();
        while(data != null){
            System.out.println(data);
            data=br.readLine();
        }
        br.close();
        isr.close();
        is.close();
阅读更多

javasocket

01-12

我要写一段客户端与服务器端的通信。但要求用时序也即客户端发出一个数n0(1972),then服务器端Receive n0,then服务器端发出“STEP1 DATA n1(1996);rnthen客户端receive n1,and then客户端send “STEP DATA f1(n1)”;then 服务器端receive f1(n1),and then 服务器端send“STEP2 DATA f0(n0)”;and then客户端receive f0(n0);then进行判断if f0的反函数(f0(f0(n0))!= n0 then close connection.// WorkSocket.cpp : implementation filernrnrn#include "stdafx.h"rn#include "Comm.h"rn#include "WorkSocket.h"rnrn#ifdef _DEBUGrn#define new DEBUG_NEWrn#undef THIS_FILErnstatic char THIS_FILE[] = __FILE__;rn#endifrnrnextern int Count;rnextern HANDLE HMutex;rnrn/////////////////////////////////////////////////////////////////////////////rn// CWorkSocketrnrnCWorkSocket::CWorkSocket()rnrn m_n1=1996;rn m_n0=0;rn m_f1n1=0;rn m_f0n0=0;rn m_try=0;rn bStep1=TRUE;rn bStep2=FALSE;rn bStep3=FALSE;rn bStep4=FALSE;rnrnrnCWorkSocket::~CWorkSocket()rnrnrnrnrn// Do not edit the following lines, which are needed by ClassWizard.rn#if 0rnBEGIN_MESSAGE_MAP(CWorkSocket, CAsyncSocket)rn //AFX_MSG_MAP(CWorkSocket)rn //AFX_MSG_MAPrnEND_MESSAGE_MAP()rn#endif // 0rnrn/////////////////////////////////////////////////////////////////////////////rn// CWorkSocket member functionsrnrnvoid CWorkSocket::OnClose(int nErrorCode) rnrn // TODO: Add your specialized code here and/or call the base classrn if (nErrorCode!=0)rn rn AfxMessageBox("CWorkSocket::OnClose ERROR!");rn return;rn rn this->Close();rnrn ::WaitForSingleObject(HMutex,INFINITE);rn --Count;rn CString ro;rn ro.Format("Have %d Threads...",Count); rn AfxMessageBox(ro);rn ::ReleaseMutex(HMutex);rnrn CAsyncSocket::OnClose(nErrorCode);rnrnrnvoid CWorkSocket::OnReceive(int nErrorCode) rnrn // TODO: Add your specialized code here and/or call the base classrn if (nErrorCode!=0)rn rn AfxMessageBox("CWorkSocket::OnReceive ERROR!");rn return;rn rn rn /*rn UINT port;rn CString address,response;rnrn this->GetPeerName(address,port);rn response.Format("You come from %s :%d! \r\n\r\n",address,port);rn this->Send(response,response.GetLength());rn */rn rn char Buf[512];rn int iRcvd;rn CString strRecvd;rn int iStep;rnrn iRcvd=this->Receive(Buf,511);rn if (iRcvd == SOCKET_ERROR)rn rn AfxMessageBox("CWorkSocket::OnReceive Receive Data Error!");rn return;rn rn elsern rn Buf[iRcvd] = NULL;rn strRecvd = Buf;rn rnrn BOOL bGo=TRUE;rn CString strSend=_T("");rn CString strResult=_T("");rn int iResult=0;rn while(bGo)rn rn iStep=strRecvd.Find("STEP1");rn if (iStep>=0 && bStep1)rn rn iStep=strRecvd.Find("DATA");rn strResult=strRecvd.Right(strRecvd.GetLength()-iStep-4);rn iResult=atoi(strResult);rn m_n0=iResult; rn m_f0n0=F0(m_n0);rnrn strSend.Format("STEP1 DATA %d",m_n1);rn this->Send(strSend,strSend.GetLength());rn bStep1=FALSE;rn bStep2=TRUE;rn bGo=FALSE;rn break;rn rnrn iStep=strRecvd.Find("STEP2");rn if (iStep>=0 && bStep2)rn rn iStep=strRecvd.Find("DATA");rn strResult=strRecvd.Right(strRecvd.GetLength()-iStep-4);rn iResult=atoi(strResult);rn m_f1n1=iResult;rn rn if( F1R1(m_f1n1)!=m_n1)rn rn rn strSend=_T("No Credit");rn this->Send(strSend,strSend.GetLength());rn this->Close();rn return;rn rnrn strSend.Format("STEP2 DATA %d",m_f0n0);rn this->Send(strSend,strSend.GetLength());rn rn bStep2=FALSE;rn bStep3=TRUE;rn bGo=FALSE;rn break;rn rnrn iStep=strRecvd.Find("STEP3");rn if (iStep>=0 && bStep3)rn rn iStep=strRecvd.Find("USER");rn strResult=strRecvd.Right(strRecvd.GetLength()-iStep-4);rn strResult.TrimLeft();rn strResult.TrimRight();rn iStep=strResult.Find("PASS");rnrn CString user=_T(""),pass=_T("");rn user=strResult.Left(iStep);rn user.TrimLeft();rn user.TrimRight();rn pass=strResult.Right(strResult.GetLength()-iStep-4);rn pass.TrimLeft();rn pass.TrimRight();rn rn switch (Authenticate(user,pass))rn rn case 0:rn strSend=_T("STEP3 AUTH OK MESS ");rn bStep3=FALSE;rn bStep4=TRUE;rn break;rn case 1:rn strSend=_T("STEP3 AUTH OK MESS ");rn strSend+=_T("CHAT_FLAG");rn bStep3=FALSE;rn bStep4=TRUE;rn break;rn case 3:rn strSend=_T("STEP3 AUTH OK MESS ");rn strSend+=_T("MAIL_FLAG");rn bStep3=FALSE;rn bStep4=TRUE;rn break;rn case 4:rn strSend=_T("STEP3 AUTH OK MESS ");rn strSend+=_T("CHAT_FLAG MAIL_FLAG");rn bStep3=FALSE;rn bStep4=TRUE;rn break;rn case 5:rn strSend=_T("STEP3 AUTH OK MESS ");rn strSend+=_T("MANAGE_FLAG");rn bStep3=FALSE;rn bStep4=TRUE;rn break;rn case 6:rn strSend=_T("STEP3 AUTH OK MESS ");rn strSend+=_T("CHAT_FLAG MANAGE_FLAG");rn bStep3=FALSE;rn bStep4=TRUE;rn break;rn case 8:rn strSend=_T("STEP3 AUTH OK MESS ");rn strSend+=_T("MAIL_FLAG MANAGE_FLAG");rn bStep3=FALSE;rn bStep4=TRUE;rn break;rn case 9:rn strSend=_T("STEP3 AUTH OK MESS ");rn strSend+=_T("CHAT_FLAG MAIL_FLAG MANAGE_FLAG");rn bStep3=FALSE;rn bStep4=TRUE;rn break;rn case -1:rn strSend=_T("STEP3 ERROR LOGIN");rn bStep3=TRUE;rn break;rn default:rn strSend=_T("STEP3 ABORT RETRY CREDIT");rn bStep3=FALSE;rn bStep1=TRUE;rn break;rn rn ++m_try;rn if(m_try>2) rn rn strSend=_T("REACH MAX ERROR LOGIN");rn this->Send(strSend,strSend.GetLength());rn this->Close();rn rn this->Send(strSend,strSend.GetLength());rn rn bGo=FALSE;rn break;rn rn rn iStep=strRecvd.Find("STEP4");rn if (iStep>=0 && bStep4)rn rn iStep=strRecvd.Find("OK");rn if(iStep>=0)rn AfxMessageBox("LOGIN SUCCESS!");rn elsern AfxMessageBox("LOGIN FAIL!");rn rn bStep4=FALSE;rn bGo=FALSE;rn break;rn rnrn strSend=_T("OTHER ERROR");rn this->Send(strSend,strSend.GetLength());rn rn bGo=FALSE; rn break;rn rnrn CAsyncSocket::OnReceive(nErrorCode);rnrnrnint CWorkSocket::F1(int n)rnrn return (n*3-5);rnrnrnint CWorkSocket::F1R1(int n)rnrn return ((n+5)/3);rnrnrnint CWorkSocket::F0(int n)rnrn return (n*5 -3);rnrnrnint CWorkSocket::Authenticate(CString user, CString pass)rnrn return 9;rnrnrn//rn#if !defined(AFX_WORKSOCKET_H__212668C0_E373_11D4_AD49_0000E818C2D1__INCLUDED_)rn#define AFX_WORKSOCKET_H__212668C0_E373_11D4_AD49_0000E818C2D1__INCLUDED_rnrn#if _MSC_VER > 1000rn#pragma oncern#endif // _MSC_VER > 1000rn// WorkSocket.h : header filern//rnrnrnrn/////////////////////////////////////////////////////////////////////////////rn// CWorkSocket command targetrnrnclass CWorkSocket : public CAsyncSocketrnrn// Attributesrnpublic:rnrn// Operationsrnpublic:rn CWorkSocket();rn virtual ~CWorkSocket();rnrn// Overridesrnpublic:rn rn // ClassWizard generated virtual function overridesrn //AFX_VIRTUAL(CWorkSocket)rn public:rn virtual void OnClose(int nErrorCode);rn virtual void OnReceive(int nErrorCode);rn //AFX_VIRTUALrnrn // Generated message map functionsrn //AFX_MSG(CWorkSocket)rn // NOTE - the ClassWizard will add and remove member functions here.rn //AFX_MSGrnrn// Implementationrnprotected:rnprivate:rn BOOL bStep1;rn BOOL bStep2;rn BOOL bStep3;rn BOOL bStep4;rn int m_try;rn int Authenticate(CString user,CString pass);rn int F0(int n);rn int F1(int n);rn int F1R1(int n);rn int m_n1;rn int m_n0;rn int m_f1n1;rn int m_f0n0;rn;rnrn/////////////////////////////////////////////////////////////////////////////rnrn//AFX_INSERT_LOCATIONrn// Microsoft Visual C++ will insert additional declarations immediately before the previous line.rnrn#endif // !defined(AFX_WORKSOCKET_H__212668C0_E373_11D4_AD49_0000E818C2D1__INCLUDED_)rn//rn#if !defined(AFX_SERVERSOCKET_H__212668BE_E373_11D4_AD49_0000E818C2D1__INCLUDED_)rn#define AFX_SERVERSOCKET_H__212668BE_E373_11D4_AD49_0000E818C2D1__INCLUDED_rnrn#if _MSC_VER > 1000rn#pragma oncern#endif // _MSC_VER > 1000rn// ServerSocket.h : header filern//rnrnrnrn/////////////////////////////////////////////////////////////////////////////rn// CServerSocket command targetrnrnclass CServerSocket : public CAsyncSocketrnrn// Attributesrnpublic:rnrn// Operationsrnpublic:rn CServerSocket();rn CServerSocket(UINT SocketNo);rn virtual ~CServerSocket();rnrn// Overridesrnpublic:rn // ClassWizard generated virtual function overridesrn //AFX_VIRTUAL(CServerSocket)rn public:rn virtual void OnAccept(int nErrorCode);rn virtual void OnClose(int nErrorCode);rn //AFX_VIRTUALrnrn // Generated message map functionsrn //AFX_MSG(CServerSocket)rn // NOTE - the ClassWizard will add and remove member functions here.rn //AFX_MSGrnrn// Implementationrnprotected:rnprivate:rn BOOL bStopAccept;rn;rnrn/////////////////////////////////////////////////////////////////////////////rnrn//AFX_INSERT_LOCATIONrn// Microsoft Visual C++ will insert additional declarations immediately before the previous line.rnrn#endif // !defined(AFX_SERVERSOCKET_H__212668BE_E373_11D4_AD49_0000E818C2D1__INCLUDED_)rnrn//rn// CommDlg.h : header filern//rnrn#if !defined(AFX_COMMDLG_H__212668B6_E373_11D4_AD49_0000E818C2D1__INCLUDED_)rn#define AFX_COMMDLG_H__212668B6_E373_11D4_AD49_0000E818C2D1__INCLUDED_rnrn#include "ServerSocket.h" // Added by ClassViewrn#if _MSC_VER > 1000rn#pragma oncern#endif // _MSC_VER > 1000rnrn/////////////////////////////////////////////////////////////////////////////rn// CCommDlg dialogrnrnclass CCommDlg : public CDialogrnrn// Constructionrnpublic:rn CServerSocket test;rn CCommDlg(CWnd* pParent = NULL); // standard constructorrnrn// Dialog Datarn //AFX_DATA(CCommDlg)rn enum IDD = IDD_COMM_DIALOG ;rn // NOTE: the ClassWizard will add data members herern //AFX_DATArnrn // ClassWizard generated virtual function overridesrn //AFX_VIRTUAL(CCommDlg)rn protected:rn virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV supportrn //AFX_VIRTUALrnrn// Implementationrnprotected:rn HICON m_hIcon;rnrn // Generated message map functionsrn //AFX_MSG(CCommDlg)rn virtual BOOL OnInitDialog();rn afx_msg void OnPaint();rn afx_msg HCURSOR OnQueryDragIcon();rn //AFX_MSGrn DECLARE_MESSAGE_MAP()rn;rnrn//AFX_INSERT_LOCATIONrn// Microsoft Visual C++ will insert additional declarations immediately before the previous line.rnrn#endif // !defined(AFX_COMMDLG_H__212668B6_E373_11D4_AD49_0000E818C2D1__INCLUDED_)rnrnrn

没有更多推荐了,返回首页