程序功能:
开启服务端 -> 客户端发送消息到服务端 -> 服务端打印接收到的消息 -> 服务端返回一个消息给客户端 -> 客户端接收服务端返回的消息并打印
package com.zf.test05;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server04 {
public static void main(String[] args) throws Exception {
final String message = "server message";
ServerSocket serverSocket = new ServerSocket(8888) ;
System.out.println("server start success...");
Socket client = serverSocket.accept();
InputStream is = client.getInputStream() ;
// receive msg
ByteArrayOutputStream baos = new ByteArrayOutputStream() ;
byte[] buf = new byte[1];
int len = -1;
while((len = is.read(buf)) != -1){
System.out.println("client:read msg once");
baos.write(buf , 0 , len);
baos.flush();
}
byte[] receiveDatas = baos.toByteArray() ;
System.out.printf("server:message:%s%n"
,new String(receiveDatas));
//send msg
OutputStream os = client.getOutputStream() ;
os.write(message.getBytes());
os.flush();
client.shutdownOutput(); //如果不调用该方法,另一端的read方法讲一直阻塞。
System.out.println("server:send message success...");
client.close();
serverSocket.close();
}
}
package com.zf.test05;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Client04 {
public static void main(String[] args) throws Exception {
final String message = "client message";
Socket socket = new Socket("127.0.0.1" , 8888);
OutputStream os = socket.getOutputStream() ;
//send msg
os.write(message.getBytes());
os.flush();
socket.shutdownOutput(); //如果不调用该方法,另一端的read方法讲一直阻塞。
System.out.println("client:send message success!");
// receive msg
InputStream is = socket.getInputStream() ;
ByteArrayOutputStream baos = new ByteArrayOutputStream() ;
byte[] buf = new byte[1];
int len = -1;
while((len = is.read(buf)) != -1){
System.out.println("client:read msg once");
baos.write(buf , 0 , len);
baos.flush();
}
byte[] receiveDatas = baos.toByteArray() ;
System.out.printf("client:message:%s%n" ,
new String(receiveDatas));
socket.close();
}
}