欢迎来到天天文库
浏览记录
ID:37758066
大小:35.00 KB
页数:4页
时间:2019-05-30
《实验三 基于TCP协议的Socket编程》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、实验三基于TCP协议的Socket编程实验目的1、掌握基于TCP协议的Socket概念2、学习编写基于TCP协议的Socket程序实验内容1.编写一个Client/Server程序对,服务器只要求每次处理一个请求。客户端向服务器报上自己的名字,服务器向客户端问好。参照下面程序客户端程序:importjava.io.*;importjava.net.*;publicclassClient11{publicstaticvoidmain(Stringargs[])throwsException{Socketsk=newSocket("127.0.0.1",5000);OutputStreamo
2、s=sk.getOutputStream();OutputStreamWriterow=newOutputStreamWriter(os);PrintWriterpw=newPrintWriter(ow);pw.println("Peter");pw.flush();InputStreamis=sk.getInputStream();InputStreamReaderir=newInputStreamReader(is);BufferedReaderbr=newBufferedReader(ir);Strings=br.readLine();System.out.println(s);p
3、w.close();br.close();sk.close();}}服务器端程序:importjava.io.*;importjava.net.*;publicclassServer11{publicstaticvoidmain(Stringargs[])throwsException{ServerSocketsrsk=newServerSocket(5000);while(true){Socketk=srsk.accept();InputStreamis=k.getInputStream();InputStreamReaderir=newInputStreamReader(is);Bu
4、fferedReaderbr=newBufferedReader(ir);Strings=br.readLine();OutputStreamos=k.getOutputStream();OutputStreamWriterow=newOutputStreamWriter(os);PrintWriterpw=newPrintWriter(ow);pw.println("Hello!"+s);pw.flush();pw.close();br.close();k.close();}}}2.将上题改写成一个多线程的服务器程序。importjava.io.*;importjava.net.*;p
5、ublicclassServer11{publicstaticvoidmain(Stringargs[])throwsException{ServerSocketsrsk=newServerSocket(5000);while(true){Socketk=srsk.accept();ServerThreadst=newServerThread(k);st.start();}}}classServerThreadextendsThread{Socketsk=null;ServerThread(Sockett){sk=t;}publicvoidrun(){try{InputStreamis=
6、sk.getInputStream();InputStreamReaderir=newInputStreamReader(is);BufferedReaderbr=newBufferedReader(ir);Strings=br.readLine();OutputStreamos=sk.getOutputStream();OutputStreamWriterow=newOutputStreamWriter(os);PrintWriterpw=newPrintWriter(ow);pw.println("Hello!"+s);pw.flush();pw.close();br.close()
7、;sk.close();}catch(Exceptione){System.out.println(e);}}}3.编写一个基于TCP协议的网络聊天程序。importjava.io.*;importjava.net.*;publicclassTCPServer{publicstaticvoidmain(String[]args)throwsException{ServerSocketsvsk=newServerSocket(1000
此文档下载收益归作者所有