資源描述:
《java_socket_編程》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫。
1、主要內(nèi)容TCP協(xié)議Socket編程1UDP協(xié)議Socket編程2Socket編程實(shí)例3JavaMail郵件編程4Socket通訊網(wǎng)絡(luò)上的兩個(gè)程序通過一個(gè)雙向的通訊連接實(shí)現(xiàn)數(shù)據(jù)的交換,這個(gè)雙向鏈路的一端稱為一個(gè)Socket。Socket通常用來實(shí)現(xiàn)客戶方和服務(wù)方的連接。兩類傳輸協(xié)議TCP(TransportControlProtocol)面向連接的能夠提供可靠的流式數(shù)據(jù)傳輸?shù)膮f(xié)議。類似于打電話的過程。URL,URLConnection,Socket,ServerSocket等類都使用TCP協(xié)議進(jìn)行網(wǎng)絡(luò)通訊。UDP(UserDatagramProtocol)非面向連接
2、的提供不可靠的數(shù)據(jù)包式的數(shù)據(jù)傳輸?shù)膮f(xié)議。類似于從郵局發(fā)送信件的過程。DatagramPacket,DatagramSocket,MulticastSocket等類使用UDP協(xié)議進(jìn)行網(wǎng)絡(luò)通訊。1.TCP協(xié)議Socket編程Java中與Socket編程相關(guān)的包:importjava.io.*;importjava.net.*;Java中提供了兩類的TCPSocket:服務(wù)器端:java.net.Serversocket客戶端:java.net.socket2.TCPSocket通信的過程Client-serverandServiceServerClientServic
3、eshttp(80)SMTP(25)FTP(21)Telnet(23)Socket通信過程(1)服務(wù)器建立監(jiān)聽進(jìn)程,監(jiān)聽每個(gè)端口是否要求進(jìn)行通信.(2)客戶端創(chuàng)建一個(gè)Socket對(duì)象,向服務(wù)器端發(fā)送連接請(qǐng)求.(3)服務(wù)器監(jiān)聽到客戶端的連接請(qǐng)求,創(chuàng)建一個(gè)Socket,與客戶端進(jìn)行通信.(4)建立接收和發(fā)送兩個(gè)緩存區(qū),并打開Socket及其輸入、輸出流.(5)根據(jù)協(xié)議讀寫Socket內(nèi)容.(6)通信結(jié)束后關(guān)閉Socket.Socket通信過程newSocketnewSocketServerSocketClientServerRead/WriteDataRead/Wri
4、teDataCloseSocketCloseSocketwaitrequestconnectacceptsendI/Ostreamreceivereceivesendclosedisconnectclose服務(wù)器端常用函數(shù)PublicServerSocket(port)throwsIOExceptionPublicAccept()throwsIOExceptionPublicclose()throwsIOExceptionPublicSetSoTimeout(inttimeout)throwsIOException//設(shè)置最大監(jiān)聽時(shí)間客戶端常用函數(shù)PublicSo
5、cket(address,port)throwsIOExceptionPublicvoidclose()throwsIOExceptionPublicInetAddressgetInetAddress()PublicInputStreamgetInputStream()throwsIOExceptionPublicInetAddressgetlocalAddress()PublicintgetLocalPort()PublicOutputStreamgetOutputStream()throwsIOException客戶端常用函數(shù)PublicintgetRecei
6、veBufferSize()throwsSocketExceptionPublicintgetSendBufferSize()throwsSocketExceptionPublicbooleanisClosed()PublicbooleanisConnectedPublicvoidsetSendBufferSize(intsize)throwsSocketExceptionPublicvoidsetReceiveBufferSize(intsize)throwsSocketExceptionSocket通信模式單線程Socket通信多用戶排隊(duì)Socket通信多線程
7、Socket通信創(chuàng)建socketSocket(InetAddressaddress,intport);Socket(InetAddressaddress,intport,booleanstream);Socket(Stringhost,intport);Socket(Stringhost,intport,booleanstream);ServerSocket(intport);ServerSocket(intport,intcount);客戶端Socket的建立try{Socketsocket=newSocket(”127.0.0.1",2000);}catch(
8、IOExc