Java网络编程技术-02_第1页
Java网络编程技术-02_第2页
Java网络编程技术-02_第3页
Java网络编程技术-02_第4页
Java网络编程技术-02_第5页
已阅读5页,还剩54页未读 继续免费阅读

下载本文档

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

文档简介

第2章TCP协议网络编程12.1Socket通信在Java中,基于TCP协议实现网络通信的类有两个:1.在客户端的Socket类2.在效劳器端的ServerSocket类基于TCP协议实现网络通信连接过程:在效劳器端通过指定一个用来等待的连接的端口号创立一个ServerSocket实例。调用ServerSocket类的accept方法使效劳器处于阻塞状态,等待用户请求。在客户端通过规定一个主机和端口号创立一个socket实例,连到效劳器上。2

构造方法:

publicSocket()publicSocket(String

host,int

port)publicSocket(InetAddress

address,int

port)publicSocket(InetAddress

address,int

port,InetAddress

localAddr,int

localPort)

在JDK1.1以前,Socket类可同时用于TCP/UDP通信:publicSocket(String

host,int

port,boolean

stream)

publicSocket(InetAddress

host,int

port,boolean

stream)这些方法都将抛出异常IOException,程序中需要捕获处理。Socket

类3

输入/输出流管理publicInputStreamgetInputStream()publicvoidshutdownInput()publicOutputStreamgetOutputStream()publicvoidshutdownOutput()这些方法都将抛出例外IOException,程序中需要捕获处理。

关闭Socketpublicvoidclose()throwsIOException

设置/获取Socket数据publicInetAddressgetInetAddress()publicintgetPort()publicvoidsetSoTimeout(int

timeout)….这些方法都将抛出例外SocketException,程序中需要捕获处理。Socket类的主要方法4构造方法:publicServerSocket(int

port)publicServerSocket(int

port,int

backlog):支持指定数目的连接publicServerSocket(int

port,int

backlog,InetAddress

bindAddr)这些方法都将抛出例外IOException,程序中需要捕获处理。ServerSocket类5ServerSocket类主要方法publicSocketaccept():等待客户端的连接publicvoidclose():关闭SocketpublicInetAddressgetInetAddress()、publicintgetLocalPort(),…publicvoidsetSoTimeout(int

timeout),…这些方法都将抛出例外SocketException,程序中需要捕获处理。6无论一个Socket通信程序的功能多么齐全、程序多么复杂,其根本结构都是一样的,都包括以下四个根本步骤:1、在客户方和效劳器方创立Socket/ServerSocket。2、翻开连接到Socket的输入/输出流。3、利用输入/输出流,按照一定的协议对Socket进行读/写操作。4、关闭输入/输出流和Socket。通常,程序员的主要工作是针对所要完成的功能在第3步进行编程,第1、2、4步对所有的通信程序来说几乎都是一样的。7ServerServerSocket(port#)Socketsocket=ServerSocket.accept()接收连接OutputStreamInputStreamCloseSocketClientSocket(host,port#)与服务器建立连接OutputStreamInputStreamCloseSocketsocket81、建立Socket在客户端:try{Socketclient=newSocket(host,4444);}catch(IOExceptione){}在效劳器端:try{ServerSocketserver=newServerSocket(4444);}catch(IOExceptione){}Socketsocket=null;try{socket=server.accept();//等待客户端连接}catch(IOExceptione){}92、在客户端和效劳器端同时翻开输入/输出流类Socket提供了方法getInputStream()和getOutputStream()来得到Socket对应的输入/输出流以进行数据读写操作,它们分别返回InputStream对象和OutputStream对象。为了便于读写数据,应在返回的输入/输出流对象上建立过滤流,如DataInputStram/DataOutputStram、BufferedInputStream/BufferedOutputStream、PrintStream;InputStreamReader/OutputStreamWriter、BufferedReader/BufferedWriter、PrintWriter等。BufferedReader=newBufferedReader(newInputStreamReader(socket.getInputStream()));BufferedWriter=newBufferedWriter(newInputStreamWriter(socket.getOutputStream()));3、关闭输入/输出流和Socket在客户端和效劳器端分别关闭输入/输出流和Socket:先关闭所有相关的输入/输出流,在关闭Socket。10创建服务器(端口号)定义数据成员服务器等待网络连接建立socket流发送谈话信息接收用户谈话信息创建Socket实例定义数据成员建立socket流发送谈话信息接收服务器谈话信息关闭流accept()44444444结束谈话(Bye.)结束谈话(Bye.)关闭流服务器端客户端11SingleTalkClient.java看看这个谈话程序的运行效果:2、客户端SingleTalkServer.java1、效劳器端12简单的Client/Server在本地机器上测试网络程序用缭绕地址Socketsocket=newSocket(“”,4444);建立socket连接后,还应该建立输入输出数据流。要控制好输入/输出流和Socket关闭的时间。如果网络的一端已经关闭,另一端读到null。在运行时,效劳器端程序一般应先行启动。13Server1(1111)client(2222)Server2(2222)client(1111)Server解决方案一:在一台计算机上一次启动多个效劳器程序,只要端口号不同。myserver1<-------->myclient1myserver2<-------->myclient2支持多Client14解决方案二:将效劳器写成多线程的,不同的处理线程为不同的客户效劳。主线程只负责循环等待,处理线程负责网络连接,接收客户输入的信息。//主线程while(true){acceptaconnection;createathreadtodealwiththeclient;}endwhileServerclient1client2serverthread2serverthread1……15serverSocket=newServerSocket(4444);while(listening){Socketsocket;socket=serverSocket.accept();//程序将在此等候客户端的连接newMultiTalkServerThread(socket,clientNumber).start();clientNumber++;//记录客户数目}serverSocket.close();classMultiTalkServerThreadextendsThread{publicMultiTalkServerThread(Socketsocket,intclientNumber){this.socket=socket;this.clientNumber=clientNumber+1;}publicvoidrun(){…}}16客户1客户2服务器线程1()线程2()MultiTalkServer.java17Client之间通过Server通信可以在效劳器端将与各客户进行通信的Socket和线程管理起来,从而各客户之间可以在效劳器端的协助下进行通信。服务器(4444)acceptsocket客户2IP1client1线程1客户1IP2client2线程2182.2TCP网络编程案例〔1〕网络版的hello,world!程序。〔2〕简单的多人聊天(群聊)程序〔3〕GUI界面〔4〕有GUI界面的简单聊天程序〔5〕多线程实现有GUI界面的简单聊天程序〔6〕有GUI界面的简单的多人聊天聊天程序19.*;ServerSoket类构造方法:ServerSocket(intport)方法:Socketaccept();Socket类构造方法:Socket(Stringhost,intport);方法:InputStereamgetInputStream();OutputStreamgetOutputStream();20java.io.*;DataInputStream类构造方法:DataInputStream(InputStreamins);方法:StringreadUTF();DataOutputStream类构造方法:DataOutputStream(OutputStreamins)方法:voidwriteUTF();21〔1〕网络版的hello,world!程序

1〕Serverimportjava.io.*;import.*;public

classmyServer{public

static

voidmain(String[]args)throwsIOException{ServerSockets=newServerSocket(8888);Socketss=s.accept();OutputStreamos=ss.getOutputStream();DataOutputStreamdataout=newDataOutputStream(os);dataout.writeUTF("hello,world!");dataout.close();s.close();ss.close();}}222〕Clientimportjava.io.*;import.*;public

classclient{public

static

voidmain(String[]args)throwsIOException{Sockets=newSocket("",8888);InputStreamin=s.getInputStream();DataInputStreamdataIn=newDataInputStream(in);System.out.println(dataIn.readUTF());}}23〔2〕简单的多人聊天〔群聊〕程序

1〕Serverimportjava.io.*;import.*;importjava.util.*;public

classmyServer{public

staticArrayList<Socket>socketlist=newArrayList<Socket>();public

static

voidmain(String[]args)throwsIOException{ServerSocketss=newServerSocket(9999);while(true){Sockets=ss.accept();socketlist.add(s);Threadt=newThread(newserverThread(s));t.start();}}}242〕Server多线程类importjava.io.*;import.*;import

java.util.*;public

classmyServerThreadimplementsRunnable{Sockets=null;DataInputStreamdatain=null;DataOutputStreamdataout=null;publicmyServerThread(Sockets)throwsIOException{this.s=s;datain=newDataInputStream(s.getInputStream());}public

voidrun(){try{Stringc=null;while((c=readFromClient())!=null){25

for(Sockets:myServer.socketList){dataout=newDataOutputStream(s.getOutputStream());dataout.writeUTF(c);}}}catch(IOExceptione){}}privateStringreadFromClient(){try{returndatain.readUTF();}catch(IOExceptione){myServer.socketList.remove(s);}return

null;}}263〕Clientimportjava.io.*;import.*;public

classmyClient{public

static

voidmain(String[]args)throwsIOException{Sockets=newSocket("",7000);myClientThreadct=newmyClientThread(s);Threadt=newThread(ct);t.start();DataOutputStreamdataout=newDataOutputStream(s.getOutputStream());Stringline=null;InputStreamReaderir=newInputStreamReader(System.in);BufferedReaderbr=newBufferedReader(ir);while((line=br.readLine())!=null){dataout.writeUTF(line);}}}274〕Client多线程类importjava.io.*;import.*;public

classmyClientThreadimplementsRunnable{Sockets=null;DataInputStreamdatain=null;publicmyClientThread(Socketss)throwsIOException{s=ss;datain=newDataInputStream(s.getInputStream());}28public

voidrun(){try{Stringcontent=null;while((content=datain.readUTF())!=null){System.out.println(content);}}catch(Exceptionex){}}}29〔3〕GUI界面public

classGUI{public

static

voidmain(String[]args){newmyGUI("hello!");}}30importjava.awt.*;import.*;public

class

myGUI

extendsFrame{Panelp1,p2;Buttonbs,bl,bx;TextAreat1;Labell1,l2;TextFieldtt1,tt2;publicmyGUI(Strings){super(s);p1=newPanel();p2=newPanel();t1=newTextArea(12,75);l1=newLabel("消息:");l2=newLabel("昵称:");tt1=newTextField("那你就去吧,别让妖精迷住你",36);tt2=newTextField("八戒",6);bs=newButton("发送");bl=newButton("连接");31addWindowListener(newWindowAdapter(){public

voidwindowClosing(WindowEvente){System.exit(0);}});setLayout(newFlowLayout());p1.setLayout(newBorderLayout());p1.add(t1);add(p1);p2.setLayout(newFlowLayout());p2.add(bl);p2.add(l2);p2.add(tt2);p2.add(l1);p2.add(tt1);p2.add(bs);add(p2);setBounds(100,100,600,280);setVisible(true);}}32〔4〕有GUI界面的简单聊天程序

1〕Serverpublic

classmyServer{public

static

voidmain(String[]args){newsFrame("ChatroomSever");}}33importjavax.swing.*;import.*;importjava.io.*;import.*;importjava.awt.*;public

class

sFrame

extendsJFrame{ServerSocketserver=null;Sockets=null;DataInputStreamdataIn=null;DataOutputStreamdataout=null;Panelp1,p2;Buttonbs,bl,bb;TextAreat1;TextFieldt2;34publicsFrame(Stringss){super(ss);p1=newPanel();p2=newPanel();t1=newTextArea();bb=newButton("接收消息");t2=newTextField("大师兄,我去捉妖精吧!",36);bs=newButton("发送");bl=newButton("启动");bl.addActionListener(newbll());bs.addActionListener(newbss());bb.addActionListener(newbbb());addWindowListener(newww());setLayout(newFlowLayout());p1.add(t1);add(p1);p2.setLayout(newFlowLayout());p2.add(bl);p2.add(bb);p2.add(t2);p2.add(bs);add(p2);setBounds(100,100,460,260);setVisible(true);}35classbllimplementsActionListener{public

voidactionPerformed(ActionEvente){try{server=newServerSocket(5000);s=server.accept();dataIn=newDataInputStream(s.getInputStream());dataout=newDataOutputStream(s.getOutputStream());}catch(Exceptione1){}}}classbssimplementsActionListener{public

voidactionPerformed(ActionEvente){

try{dataout.writeUTF("八戒说:"+t2.getText());t1.append("八戒说:"+t2.getText()+"\n");}36catch(IOExceptione1){}}}classbbbimplementsActionListener{public

voidactionPerformed(ActionEvente){

try{t1.append(dataIn.readUTF()+"\n");}catch(IOExceptiongg){}}}classwwextendsWindowAdapter{public

voidwindowClosing(WindowEventee){System.exit(0);}}}372〕Clientpublic

classmyClient{public

static

voidmain(String[]args){newcFrame("ChatroomClient");}}38importjava.awt.*;import.*;importjava.io.*;import.*;class

cFrame

extendsFrame{Sockets=null;DataInputStreamdataIn=null;DataOutputStreamdataout=null;Panelp1,p2;Buttonbs,bl,bb;TextAreat1;TextFieldt2;cFrame(Stringss){super(ss);p1=newPanel();p2=newPanel();t1=newTextArea();bb=newButton("接收消息");t2=newTextField("那你就去吧,别让妖精迷住!",36);bs=newButton("发送");bl=newButton("连接");bl.addActionListener(newbll());bs.addActionListener(newbss());bb.addActionListener(newbbb());addWindowListener(newww());setLayout(newFlowLayout());39p1.setLayout(newBorderLayout());p1.add(t1);add(p1);p2.setLayout(newFlowLayout());p2.add(bl);p2.add(bb);p2.add(t2);p2.add(bs);add(p2);setBounds(100,100,460,260);setVisible(true);}classbllimplementsActionListener{public

voidactionPerformed(ActionEvente){try{s=newSocket("localhost",5000);dataIn=newDataInputStream(s.getInputStream());dataout=newDataOutputStream(s.getOutputStream());}catch(IOExceptiongg){}}}40classbssimplementsActionListener{public

voidactionPerformed(ActionEvente){try{dataout.writeUTF("悟空说:"+t2.getText());t1.append("悟空说:"+t2.getText()+"\n");}catch(IOExceptione1){}}}classbbbimplementsActionListener{public

voidactionPerformed(ActionEvente){try{t1.append(dataIn.readUTF()+"\n");}catch(IOExceptiongg){}}}classwwextendsWindowAdapter{public

voidwindowClosing(WindowEventee){System.exit(0);}}}41〔5〕多线程实现有GUI界面的简单聊天程序

1〕Serverpublic

classmyServer{public

static

voidmain(String[]args){newsFrame("ChatroomSever");}}42importjavax.swing.*;import.*;importjava.io.*;import.*;importjava.awt.*;publicclasssFrameextendsJFrame{ ServerSocketserver=null; Sockets=null; DataInputStreamdataIn=null; DataOutputStreamdataout=null; Panelp1,p2; Buttonbs,bl,bb; TextAreat1; TextFieldt2;

43publicsFrame(Stringss) { super(ss); p1=newPanel(); p2=newPanel(); t1=newTextArea(); bb=newButton("接收消息"); t2=newTextField("大师兄,我去捉妖精吧!",36); bs=newButton("发送"); bl=newButton("启动"); bl.addActionListener(newbll()); bs.addActionListener(newbss()); bb.addActionListener(newbbb()); addWindowListener(newww()); setLayout(newFlowLayout()); p1.add(t1); add(p1); p2.setLayout(newFlowLayout()); p2.add(bl); p2.add(bb); p2.add(t2); p2.add(bs); add(p2); setBounds(100,100,460,260); setVisible(true); }

44classbllimplementsActionListener { publicvoidactionPerformed(ActionEvente) {

try { server=newServerSocket(5000); s=server.accept(); dataIn=newDataInputStream(s.getInputStream()); dataout=newDataOutputStream(s.getOutputStream()); newtt().start(); } catch(Exceptione1){} } } classbssimplementsActionListener { publicvoidactionPerformed(ActionEvente) { try { dataout.writeUTF("八戒说:"+t2.getText()); t1.append("八戒说:"+t2.getText()+"\n"); } catch(IOExceptione1){} } }45 classbbbimplementsActionListener { publicvoidactionPerformed(ActionEvente) { try { t1.append(dataIn.readUTF()+"\n"); } catch(IOExceptiongg){} } } classwwextendsWindowAdapter { publicvoidwindowClosing(WindowEventee) { System.exit(0); } } classttextendsThread { publicvoidrun() { while(true) { try { t1.append(dataIn.readUTF()+"\n"); } catch(IOExceptiongg){} } } }}462〕Clientpublic

classmyClient{public

static

voidmain(String[]args){newcFrame("ChatroomClient");}}47〔6〕有GUI界面的简单的多人聊天聊天程序

1〕Serverimport.*;importjava.io.*;importjava.util.*;public

classmyMultiServer{public

staticArrayList<Socket>socketList=newArrayList<Socket>();public

static

voidmain(String[]args)throwsIOException{ServerSocketss=newServerSocket(7000);Sockets=null;while(true){s=ss.accept();socketList.add(s);newThread(newserverThread(s)).start();}}}48importjava.io.*;import.*;import

java.util.*;public

classserverThreadimplementsRunnable{Sockets=null;DataInputStreamdatain=null;DataOutputStreamdataout=null;publicserverThread(Sockets)throwsIOException{this.s=s;datain=newDataInputStream(s.getInputStream());}public

voidrun(){try{Stringc=null;while((c=readFromClient())!=null){for(Sockets:myMultiServer.socketList){49dataout=newDataOutputStream(s.getOutputStream());dataout.writeUTF(c);}}}catch(IOExceptione){}}privateStringreadFromClient(){try{returndatain.readUTF();}catch(IOExceptione){myMultiServer.socketList.remove(s);}return

null;}}502〕Clientpublic

classmyClient{public

static

voidmain(String[]args){newmyClientFrame("chatroom");}}51importjava.awt.*;import.*;importjava.io.*;import.*;class

cFrame

extendsFrame{Sockets=null;DataInputStreamdataIn=null;DataOutputStreamdataout=null;Panelp1,p2;Buttonbs,bl,bb;TextAreat1;TextFieldt2;52cFrame(Stringss){super(ss);p1=newPanel();p2=newPanel();t1=newTextArea();bb=newButton("接收消息");t2=newTextField("那你就去吧,别让妖精迷住!",36);bs=newButton("发送");bl=newButton("连接");bl.addActionListener(newbll());bs.addActionListener(newbss());bb.addActionListener(newbbb());addWindowListener(newww());setLayout(newFlowLayout());p1.setLayout(newBorderLayout());p1.add(t1);add(p1);p2.setLayout(newFlowLayout());p2.add(bl);p2.add(bb);p2.add(t2);p2.add(bs);add(p2);setBounds(100,100,460,260);setVisible(true);}53classbllimplementsActionListener{public

voidactionPerformed(ActionEvente){try{s=newSocket("localhost",5000);dataIn=newDataInputStream(s.getInputStream());dataout=newDataOutputStream(s.getOutputStream());newtt().start();}catch(IOExceptiongg){}}}classbssimplementsActionListener{public

voidactionPerformed(ActionEvente){try{dataout.writeUTF("悟空说:"+t2.getText());t1.append("悟空说:"+t2.getText()

温馨提示

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

评论

0/150

提交评论