简要笔记,后看
实现的是多线程的通信
服务器
public class Server {
public static void main(String[] args) {
try {
//创建ServerSocket实例
ServerSocket serverSocket=new ServerSocket(3444);
Socket socket=null;
//监听,直到有客户端的请求,将其赋给Socket
while(true){
socket=serverSocket.accept();
//开启一个线程去接待客户端传来的socket
new ServerThread(socket).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
服务器线程类
public class ServerThread extends Thread{
private Socket socket=null;
private static int count=0;
public ServerThread(Socket socket) {
// TODO Auto-generated constructor stub
this.socket=socket;
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
//从客户端获取的socket对象的获得输入的信息
InputStream in=null;
InputStreamReader inr=null;
BufferedReader br=null;
OutputStream os=null;
PrintWriter pw=null;
try {
in = socket.getInputStream();
//字节流转字符流
inr=new InputStreamReader(in);
//缓存
br=new BufferedReader(inr);
String string;
while((string=br.readLine())!=null){
System.out.println("客户端——>服务器:"+string);
}
//当在获取输出流之前,一定要关闭输入流,反之亦然,不然会报错,
socket.shutdownInput();
os=socket.getOutputStream();
pw=new PrintWriter(os);
synchronized ("123") {
pw.write("Welcome!"+"你是第"+(++count)+"个用户");
}
pw.flush();
// Thread.sleep(3000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
//关闭socket的输入流
//
socket.shutdownOutput();
//关闭其他流
br.close();
inr.close();
in.close();
pw.close();
os.close();
//关闭socket
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
客户端类
public class Client {
public static void main(String[] args) {
try {
//新建socket类,相当于向服务器发送请求
Socket socket=new Socket("localhost", 3444);
//获取socket的输出流
OutputStream os=socket.getOutputStream();
//将字节输出流转化为打印流
PrintWriter pw=new PrintWriter(os);
//写入
pw.write("登入名:adlkl;密码:sdsd4");
pw.flush();
/*
* 对于socket而言,在使用输出流时,要关闭输入流,反之同理
* 对于其他流,最好是写在最后
*/
socket.shutdownOutput();
InputStream is=socket.getInputStream();
BufferedReader br=new BufferedReader(
new InputStreamReader(is));
String string=null;
while((string=br.readLine())!=null){
System.out.println("服务器——>客户端"+string);
}
socket.shutdownInput();
//关闭操作
pw.close();
os.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("hjhjhj");
}
}
}