欢迎来到天天文库
浏览记录
ID:38681813
大小:80.65 KB
页数:6页
时间:2019-06-17
《使用TCP协议的Socket网络程序设计》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、实验名称:使用TCP协议的Socket网络程序设计实验目的:掌握Socket通讯机制,掌握Socket和ServerSocket类和相关方法。实验环境:WindowsXP,Eclipse实验内容和步骤:1、创建服务器和客户程序,在运行客户程序的计算机上输入的内容,可以在服务器屏幕上看到。2、有下面一段Server段程序,目的是能够同时服务多个客户,客户的请求是一句话(一个String)。如果这个请求的内容是字符串"plain"的话,服务器仅将"hello"字符串返回给用户。否则将用户的话追加到当前目录的文本文件Memo.txt中(路径为"Memo.txt"),并向用户返回"OK"
2、。注意Server并发的处理多用户,Memo.txt被共享,要求不能出现数据不一致。3、使用socket编写一个服务器端程序,服务器端程序在端口8888监听,如果它接到客户端发来的"hello"请求时会回应一个"hello",对客户端的其他请求不响应。源程序://Client.javaimportjava.awt.Container;importjava.awt.GridLayout;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.io.DataInputStream;
3、importjava.io.ObjectOutputStream;importjava.net.Socket;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JOptionPane;importjavax.swing.JTextField;publicclassClientextendsJFrameimplementsActionListener{JLabellMessage;JTextFieldtMessage;JButtonsendBut
4、ton,exitButton;publicstaticvoidmain(Stringargs[]){newClient();}//构造函数publicClient(){Containercontent=this.getContentPane();content.setLayout(newGridLayout(2,2));lMessage=newJLabel("请输入要发送的消息");tMessage=newJTextField();sendButton=newJButton("发送");exitButton=newJButton("退出");content.add(lMessag
5、e);content.add(tMessage);content.add(sendButton);content.add(exitButton);sendButton.addActionListener(this);exitButton.addActionListener(this);this.pack();this.setVisible(true);this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);}@OverridepublicvoidactionPerformed(ActionEvente){//TODOAuto-gener
6、atedmethodstubObjectobj=e.getSource();if(obj==sendButton){SendMessagesendMessage=newSendMessage();sendMessage.sendMsg=tMessage.getText().toString();try{Socketsocket=newSocket("127.0.0.1",8888);ObjectOutputStreamoutStream=newObjectOutputStream(socket.getOutputStream());outStream.writeObject((S
7、endMessage)sendMessage);DataInputStreaminStream=newDataInputStream(socket.getInputStream());Stringstr=inStream.readUTF();if(str.equals("wrong")){}else{JOptionPane.showMessageDialog(null,str,"服务器返回信息",JOptionPane.PLAIN_MESSAGE);socket.close();
此文档下载收益归作者所有