资源描述:
《基于tcp协议的socket编程》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、Java语言程序设计实验报告实验!实验题目:基于TCP协议的Socket编程指导老师:贺玉珍专业班级:计算机科学与技术系网络工程方向1002班姓名:任华瑞(2010100241)2013年5月10曰实验类型验证性实验室软件实验室三一、实验目的:1.掌握Java中的有关网络编程的相关类。2.练习使用这些类进行基于TCP协议的Socket网络编程。二、实验内容:分别编写一个客户端程序和一个服务端程序,两个程序能够实现通讯。三、实验代码:1.客户端界面代码(ClientFrame.java):importjava,awt-importjava.net.*;
2、importjava.awt.event•氺;publicclassClientFrame{privateFramef;privateTextFieldtf;privateButtonbut;privateTextAreata;ClientFrame(){init0;publicTextAreagetTextAreaO{returnthis,ta;publicvoidinit(){f=newFrame(〃客户端");f.setBounds(300,100,400,300);f.setLayout(newFlowLayout());tf=newText
3、Field(40);but=newButton("发送z/);ta=newTextArea(25,50);f.add(tf);f.add(but);f.add(ta);myEvent();f-setVisible(true);privatevoidmyEvent(){f.addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvcntc){System,exit(0);}});but.addActionListcncr(nowActionListcncr(){public
4、voidactionPerformed(ActionEventc){//ta.setText(tf.getText());try{DatagramSocketds二newDatagramSockct();byte[]buf=tf.getText().getBytes();DatagramPacketdp=newDatagramPacket(buf,buf.length,InetAddress.getByName(〃127.0.0.1〃),10001);ds.send(dp);ta.append("客广端说::〃+tf.getText()+"rrT
5、);tf.setText;}catch(Exceptionex){ex.toStringO;}finally{//ds.closeO;});}2.服务端界面代码(ServerFrame.java):importjava,net-DatagramPacket;importjava.net.DatagramSocket;importjava.net.SocketException;publicclassServerFrame{privateFramef;privateTextFieldtf;privateButtonbut;privateTcxtArca
6、ta;privateDatagramSocketdsl;ServerFrameO{init();}publicTextAreagetTextAreaO{returnthis,ta;}publicTcxtFieldgetTextFieldO{returnthis,tf;publicvoidinit(){f=newFrame(〃服务端");f.setBounds(300,100,400,300);f-setLayout(newFlowLayout());tf=newTextField(40);but=newButtonC发送");ta=newTextAr
7、ea(25,50);f.add(tf);f.add(but);f.add(ta);myEvent();f.setVisible(true);privatevoidmyEvent(){f.addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){System,exit(0);}});but.addActionListener(newActionListener(){publicvoidactionPcrformcd(ActionEvcnte)try{dsl=ne
8、wDatagramSocket();byte[]buf1=tf.getText().getBytcs();D