Java网络编程
1、服务器端向客户端输出信息
package com;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.Socket;
public class MyClientTest {
public static void main(String[] args) {
try {
//连接IP和Socket
Socket socket = new Socket("127.0.0.1",8888);
BufferedReader bf = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("服务器端输出内容为:"+bf.readLine());
bf.close();
socket.close();
//通过文件流发送消息
// OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
// BufferedWriter bw = new BufferedWriter(osw);
// bw.write("hello world");
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务器端
public class MyServerTest {
public static void main(String[] args) {
try {
//创建ServerSocket,在8888端口监听
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器端运行,等待客户端连接");
//监听,直到某个客户端连接上,成功就会得到Socket,它就像是一个连接的管道
Socket socketServer = serverSocket.accept();
PrintStream print = new PrintStream(socketServer.getOutputStream());
print.print("hello,client!");
print.close();
socketServer.close();
serverSocket.close();
//读取从客户端放松的信息
// BufferedReader br = new BufferedReader(new InputStreamReader(socketServer.getInputStream()));
// System.out.println(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端向服务器端输出信息
package com;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.Socket;
public class MyClientTest {
public static void main(String[] args) {
try {
//连接IP和Socket
Socket socket = new Socket("127.0.0.1",8888);
//通过文件流发送消息
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("hello world");
bw.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务器端
public class MyServerTest {
public static void main(String[] args) {
try {
//创建ServerSocket,在8888端口监听
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器端运行,等待客户端连接");
//监听,直到某个客户端连接上,成功就会得到Socket,它就像是一个连接的管道
Socket socketServer = serverSocket.accept();
//读取从客户端发送的信息
BufferedReader br = new BufferedReader(new InputStreamReader(socketServer.getInputStream()));
System.out.println(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Java网络编程
最新推荐文章于 2023-09-01 21:28:41 发布