客户端

向服务器端发数据并且接收服务器的响应

package com.imooc.myFirestSocket;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {

public static void main(String[] args) throws Exception {

// 创建一个socket对象
Socket socket = new Socket("localhost", 8888);
// 获得输出流
OutputStream os = socket.getOutputStream();
// 写入数据
PrintWriter pw = new PrintWriter(os);
pw.write("用户名:admin,密码:123");
pw.flush();

// 关闭输出流
socket.shutdownOutput();

//---->下面是接受服务器发来的响应
// 从socket中读数据
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader bs = new BufferedReader(isr);
String str = "";
while ((str = bs.readLine()) != null) {
System.out.println("我是客户端,服务器回应说:" + str);
}

// 关闭输入流
socket.shutdownInput();

// 关闭输入流资源
bs.close();
isr.close();
is.close();

// 关闭输出流资源
pw.close();
os.close();

}

}

服务器端

接收客户端的请求并且响应

package com.imooc.myFirestSocket;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class Server {

public static void main(String[] args) throws Exception {
// 创建一个serverSocket对象,相当于服务器,并且自己设定端口,最好设置1024以后
ServerSocket serverSocket = new ServerSocket(8888);

// 调用accept方法监听访问的Socket
Socket socket = serverSocket.accept();

// 从socket中读数据
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader bs = new BufferedReader(isr);
String str = "";
while ((str = bs.readLine()) != null) {
System.out.println("我是服务器,客户端说:" + str);
}

// 关闭输入流
socket.shutdownInput();


//---->下面是服务器响应客户端
// 获得输出流
OutputStream os = socket.getOutputStream();
// 写入数据
PrintWriter pw = new PrintWriter(os);
pw.write("欢迎您:"+new Date().toString());
pw.flush();

// 关闭输出流资源
socket.shutdownOutput();
pw.close();
os.close();


// 关闭输入流资源
bs.close();
isr.close();
is.close();

}

}