文档详情

使用TCP协议的Socket网络程序设计.docx

发布:2017-12-09约3.48千字共6页下载文档
文本预览下载声明
实验名称:使用TCP协议的Socket网络程序设计实验目的:掌握Socket通讯机制,掌握Socket和ServerSocket类和相关方法。实验环境:Windows XP ,Eclipse实验内容和步骤:1、创建服务器和客户程序,在运行客户程序的计算机上输入的内容,可以在服务器屏幕上看到。2、有下面一段Server段程序,目的是能够同时服务多个客户,客户的请求是一句话(一个 String)。如果这个请求的内容是字符串plain的话,服务器仅将hello字符串返回给用户。否则将用户的话追加到当前目录的文本文件Memo.txt中(路径为Memo.txt),并向用户返回OK。注意Server并发的处理多用户,Memo.txt被共享,要求不能出现数据不一致。3、使用socket编写一个服务器端程序,服务器端程序在端口8888监听,如果它接到客户端发来的hello请求时会回应一个hello,对客户端的其他请求不响应。源程序://Client.javaimport java.awt.Container;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.DataInputStream;import java.io.ObjectOutputStream;import java.net.Socket;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JTextField;publicclassClientextends JFrame implements ActionListener{JLabel lMessage;JTextField tMessage;JButton sendButton,exitButton;publicstaticvoid main(String args[]){new Client();}//构造函数public Client(){Container content = this.getContentPane();content.setLayout(new GridLayout(2,2));lMessage = new JLabel(请输入要发送的消息);tMessage = new JTextField();sendButton = new JButton(发送);exitButton = new JButton(退出);content.add(lMessage);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);}@Overridepublicvoid actionPerformed(ActionEvent e) {// TODO Auto-generated method stubObject obj = e.getSource();if(obj == sendButton){SendMessage sendMessage = new SendMessage();sendMessage.sendMsg = tMessage.getText().toString();try{Socket socket = new Socket(127.0.0.1,8888);ObjectOutputStream outStream = new ObjectOutputStream(socket.getOutputStream());outStream.writeObject((SendMessage)sendMessage);DataInputStream inStream = new DataInputStream(socket.getInputStream());String str = inStream.readUTF();if(str.equals(wrong)){}else{JOptionPane.showMessageDialog(null, str
显示全部
相似文档