欢迎来到天天文库
浏览记录
ID:41037234
大小:35.00 KB
页数:4页
时间:2019-08-14
《java学习之网络编程》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、java学习之网络编程packagecom.Java.suting;importjava.io.IOException;importjava.io.InputStream;importjava.NET.Socket;importjava.util.Scanner;publicclassSocketTest{publicstaticvoidmain(String[]args){try{//新建一个Socket套接字Sockets=newSocket("java.SUN.com",80);try{InputStreaminStream=s.getInputStream();Sca
2、nnerin=newScanner(inStream);while(in.hasNextLine()){Stringline=in.nextLine();System.out.println(line);}}finally{//关闭一个套接字s.close();}}catch(IOExceptione){e.printStackTrace();}}}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~packagecom.java.suting;importjava.io.*;importjava.net.*;importjava.util.
3、*;/**Thisprogramimplementsasimpleservertoport8189andechoesback*allclientinput.*/publicclassEchoServer{publicstaticvoidmain(String[]args){try{//establishserversocketServerSockets=newServerSocket(8189);//waitforclientconnectionSocketincoming=s.accept();try{//inStream接收客户端的输入,outStream输出数据到客户端
4、InputStreaminStream=incoming.getInputStream();OutputStreamoutStream=incoming.getOutputStream();Scannerin=newScanner(inStream);PrintWriterout=newPrintWriter(outStream,true/*autoflush*/);out.println("HelooEnterBYEtoexit.");//echoclientinputbooleandone=false;while(!done&&in.hasNextLine()){Stri
5、ngline=in.nextLine();out.println("Echo:"+line);if(line.trim().equals("BYE"))done=true;}}finally{incoming.close();}}catch(IOExceptione){e.printStackTrace();}}}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~·packagecom.java.suting;importjava.io.*;importjava.net.*;importjava.util.*;/**Thisprogramimpleme
6、ntsamultithreadserverthatlistenstoport*8189andechoesbackallclientinput*/publicclassThreadEchoServer{publicstaticvoidmain(String[]args){try{inti=1;ServerSockets=newServerSocket(8189);while(true){Socketincoming=s.accept();System.out.println("Spawing"+i);//创建一个线程Runnabler=newThreadedEchoHandle
7、r(incoming,i);Threadt=newThread(r);t.start();i++;}}catch(IOExceptione){e.printStackTrace();}}}/**Thisclasshandlestheclientinputforoneserversocketconnection**/classThreadedEchoHandlerimplementsRunnable{/**Constructor*/publicThreadedEchoHandler(Socketi,int
此文档下载收益归作者所有