多线程和Socket套接字
一个进程可以有多个线程
一个线程至少会有一个进程
extends Thread类
implements Runnable接口
重写run()方法
启动线程start():1.启动一个线程 2.调用run()方法
区别:
继承Thread类 资源不共享
实现Runnable接口 资源共享 还可以继承其他类
创建对象时
继承Thread类 直接new对象
实现Runnable接口 new Thread(构造参数:Runnable接口实现类对象);
--------------------------------------
Socket:套接字
java.net包
流式套接字:基于TCP协议的Socket网络编程
---服务端(main方法):
ServerSocket serverSocket = new ServerSocket(5000); //创建服务端socket 5000端口
Socket socket = serverSocket.accept(); //等待通信
InputStream is = socket.getInputStream(); //得到输入流
BufferedReader br = new BufferedReader(new InputStreamReader(is)); //把输入流封装成缓冲字符输入流
String info;
while((info=br.readLine())!=null){
System.out.println(info);
}
OutputStream os = socket.getOutputStream();
String info = "服务端的消息";
byte[] infos = info.getBytes();
os.write(infos);
os.close();
br.close();
is.close();
socket.close();
serverSocket.close();
---客户端(main方法):
Socket socket = new Socket("localhost",); //客户端 参数1:连接到ip 本机localhost 参数2:服务端端口5000
OutputStream os = socket.getOutputStream(); //得到输出流
String info = "客户端的消息";
byte[] infos = info.getBytes();
os.write(infos);
socket.shutdownOutput(); //socket输出完了要关闭
InputStream is = socket.getInputStream(); //得到输入流
BufferedReader br = new BufferedReader(new InputStreamReader(is)); //把输入流包装成缓冲字符输入流
String temp;
while((temp = br.readLine())!=null){
System.out.println(temp);
}
br.close();
is.close();
os.close();
socket.close();
//如果传的是对象 首先user类需要实现序列化 public class User implements Serializable
客户端
new user对象...
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.write(user);
oos.close();
服务端
ObjectInputStream ois = new ObjectInputStream(is);
User user = (User)ois.readObject();
System.out.println(user.getUserName());
ois.close();
数据包式套接字:基于UDP协议的Socket网络编程
=====================多线程==============
对应每个客户请求 都要创建一个相应的线程
//线程类
public class LoginThread extends Thread{
private Socket socket;
public LoginTread(Socket socket){
this.socket = socket;
}
//处理客户端请求
public void run(){
InputStream is = socket.getInputStream(); //得到输入流
ObjectInputStream ois = new ObjectInputStream(is);
User user = (User)ois.readObject();
System.out.println(user.getUserName());
OutputStream os = socket.getOutputStream();
String info = "服务端的消息";
byte[] infos = info.getBytes();
os.write(infos);
os.close();
ois.close();
is.close();
socket.close();
}
}
//服务端
---服务端(main方法):
ServerSocket serverSocket = new ServerSocket(5000); //创建服务端socket 5000端口
while(true){ //无限循环等待客户的请求
Socket socket = serverSocket.accept(); //等待通信
LoginThread loginTread = new LoginThread(socket); //把每个客户socket传入新线程
loginThread.start(); //开启线程
}
-----------
得到客户端ip
InetAddress address = socket.getInetAddress();
String ip = address.getHostAddress();