课程设计实验报告
题 目: 简单的socket通信实验
年 月 日
1、实验目的
掌握网络服务器端和客户端通信的发包和收包的原理。 2、实验内容
(一)下载编程软件配置,编程环境。
(二)设计C/S的通信机制,画出服务器端和客户端流程图。 (三)对服务器端和客户端通信进行编程实现。 (四)对实验过程和结果进行反思总结。 3、实验步骤
(一)编程环境:eclipse(java)
(二)服务器端和客户端流程图:
(三)代码实现 客户端:
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket;
class ClientRead extends Thread { }
class ClientWrite extends Thread {
private Socket client;
public ClientRead(Socket client) { }
public void run() { }
try { }
BufferedReader br = new BufferedReader(new InputStreamReader(
client.getInputStream()));
String line = \; while (true) { }
e.printStackTrace();
line = br.readLine();
if (!\.equals(line) && line != null) { }
System.out.println(\服务器说:\ + line);
this.client = client;
} catch (IOException e) {
private Socket client;
public ClientWrite(Socket client) { }
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
client.getOutputStream()));
String str = \; while (true) {
str = input.readLine(); bw.write(str);
this.client = client;
}
}
}
}
bw.newLine(); bw.flush();
} catch (IOException e) {
e.printStackTrace();
public class ClientChat { }
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Socket client = new Socket(\, 9988); System.out.println(\客户端已经建立。。。\); // 1.启动线程用于写给服务器 new ClientRead(client).start(); // 2.启动线程用于读取服务器的数据 new ClientWrite(client).start();
服务器端:
package socket;
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket;
class ServerRead extends Thread {
private Socket s;
public ServerRead(Socket s) { }
public void run() {
this.s = s;
}
}
try {
BufferedReader br = new BufferedReader(new String line = \; while (true) { }
line = br.readLine();
if (!\.equals(line) && line != null) { }
System.out.println(\客户端说:\ + line);
InputStreamReader(s.getInputStream()));
} catch (Exception e) { }
class ServerWrite extends Thread { }
public class ServersChat {
public static void main(String[] args) throws Exception {
@SuppressWarnings(\)
ServerSocket server = new ServerSocket(9988);
System.out.println(\服务器已经建立,,等待客户端连接。。\); }
}
public ServerWrite(Socket socket) { }
public void run() {
BufferedReader input = new BufferedReader(new try {
BufferedWriter bw = new BufferedWriter(new String str = \; }
str = input.readLine(); bw.write(str); bw.newLine(); bw.flush();
this.socket = socket; private Socket socket;
InputStreamReader(System.in));
OutputStreamWriter(socket.getOutputStream()));
while (true) {
} catch (Exception e) {