服务端接收消息
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 目标:客户端发送消息,服务端接收消息
*/
public class Server {
public static void main(String[] args) {
//1、定义一个ServerSocket对象
ServerSocket ss;
//3、定义一个Socket对象
Socket socket;
//5、定义一个字节输入流对象
InputStream is;
String msg;
{
try {
//2、进行服务端的端口注册
ss = new ServerSocket(9999);
//4、、监听客户端的Socket链接请求
socket = ss.accept();
//6、从socket管道中得到一个字节输入流对象
is = socket.getInputStream();
//7、把字节输入流包装成一个缓冲字符输入流
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//服务端按照行获取消息,如果没有换行会报错
while ((msg = br.readLine()) != null){
System.out.println("服务端接收到:"+msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客户端发送消息
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
/**
* 客户端
*/
public class Client {
public static void main(String[] args) {
try {
//1、创建Socket对象请求服务端的链接
Socket socket = new Socket("127.0.0.1", 9999);
//2、从socket对象中获取一个字节输出流
OutputStream os = socket.getOutputStream();
//3、把字节输出流包装成一个打印流
PrintStream ps = new PrintStream(os);
ps.println("Hello World!");
ps.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}