单线程Server
package com.sjm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 基于tcp协议的socket通信,实现用户登录
* 服务器端
* @author adminsjm
*
*/
public class Server {
public static void main(String[]args){
try {
//1.创建服务器端serversocker,指定要绑定的端口,并监听
ServerSocket serverSocket=new ServerSocket(8888);
//2.调用accept()方法开始监听,等待客户端的连接,呈阻塞状态
System.out.println("***服务器即将启动,等待客户端的连接***");
Socket socket=serverSocket.accept();
//3.获取输入流,用来读取客户端发送的登录信息
InputStream is=socket.getInputStream();//字节输入流
InputStreamReader isr=new InputStreamReader(is);//包装为字符流
BufferedReader br=new BufferedReader(isr);//添加缓冲
String info=null;
while((info=br.readLine())!=null){
System.out.println("我是服务器,客户端说:"+info);
}
socket.shutdownInput();//关闭输入流
//4.获取输出流,响应客户端的请求
OutputStream os=socket.getOutputStream();
PrintWriter pw=new PrintWriter(os);//字节流包装为打印流
pw.write("欢迎您!");
pw.flush();//刷新缓存
//5.关闭相关资源
pw.close();
br.close();
isr.close();
is.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Client
package com.sjm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* 客户端
* @author adminsjm
*
*/
public class Client {
public static void main(String[]args) {
try {
//1.创建socket,指定服务器地址和端口
Socket socket=new Socket("localhost", 8888);
//2.获取输出流,用来向服务端发送输出信息
OutputStream os=socket.getOutputStream();//字节输出流
PrintWriter pw=new PrintWriter(os);//将输出流包装为打印流
pw.write("用户名:admin;密码:123");
pw.flush();
socket.shutdownOutput();
//获取输入流,用来读取服务器端的响应信息
InputStream is=socket.getInputStream();
// InputStreamReader isr=new InputStreamReader(is);
// BufferedReader br=new BufferedReader(isr);
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String info=null;
while((info=br.readLine())!=null){
System.out.println("我是客户端,服务端说:"+info);
}
//4.关闭相关资源
br.close();
is.close();
pw.close();
os.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}