利用Java构建客户端程序和服务器端程序都需要的MystreamSocket类,定义继承自java Socket的sendMessage和receiveMessage方法 2. 构建客户端程序 (1) 创建一个MyStreamsocket的实例对象,并将其指定接收服务器和端口号 (2) 调用该socket的receiveMessage方法读取从服务器端获得的消息 3. 构建服务器端程序 (1) 构建连接socket实例,并与指定的端口号绑定,该连接socket随时侦听客户端的连接请求 (2) 创建一个MyStreamsocket的实例对象 (3) 调用MyStreamsocket的实例对象的sendMessage方法,进行消息反馈。 4. 在实验一的聊天程序里添加发送图片和文件的功能 (1) 实现发送图片并显示图片功能。 (2) 实现发送文件并保存到指定位置功能。
时间: 2024-02-06 10:12:42 浏览: 73
下面是一个简单的MyStreamSocket类的实现:
```java
import java.io.*;
import java.net.*;
public class MyStreamSocket extends Socket {
private BufferedReader in;
private PrintWriter out;
public MyStreamSocket(String host, int port) throws IOException {
super(host, port);
initializeStreams();
}
public MyStreamSocket(Socket socket) throws IOException {
super(socket.getInetAddress(), socket.getPort());
initializeStreams();
}
private void initializeStreams() throws IOException {
in = new BufferedReader(new InputStreamReader(super.getInputStream()));
out = new PrintWriter(super.getOutputStream(), true);
}
public void sendMessage(String message) throws IOException {
out.println(message);
}
public String receiveMessage() throws IOException {
return in.readLine();
}
}
```
客户端代码:
```java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try {
// 创建MyStreamSocket实例
MyStreamSocket socket = new MyStreamSocket("localhost", 7777);
// 接收消息
String message = socket.receiveMessage();
System.out.println("Server response: " + message);
// 关闭连接
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
服务器端代码:
```java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) {
try {
// 创建ServerSocket,监听端口7777
ServerSocket serverSocket = new ServerSocket(7777);
while (true) {
// 等待客户端连接
Socket socket = serverSocket.accept();
System.out.println("Client connected: " + socket.getInetAddress().getHostAddress());
// 创建MyStreamSocket实例并发送消息
MyStreamSocket mySocket = new MyStreamSocket(socket);
mySocket.sendMessage("Hello, client!");
// 关闭连接
mySocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
发送图片和文件的功能可以通过增加文件传输的代码实现。例如,客户端发送图片的代码可以如下所示:
```java
File file = new File("image.png");
InputStream is = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
is.read(buffer, 0, buffer.length);
OutputStream os = socket.getOutputStream();
os.write(buffer, 0, buffer.length);
os.flush();
is.close();
```
而服务器端接收图片的代码可以如下所示:
```java
InputStream is = socket.getInputStream();
File file = new File("image.png");
OutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int len;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
os.close();
is.close();
```
阅读全文