简单的Socket交互案例
分为三步:
第一步:实现客户端,向服务端发送信息
第二步:实现客户端,接收客户端信息,并向客户端回复
第三步:循环监听等待客户端连接
实现案例(案例内每一步有注解,这边就不详细解释了)
第一步
package com.socket;
import java.io.*;
import java.net.Socket;
/**
* 客户端
*/
public class cline {
public static void main(String[] arg){
try {
//1、创建客户端Socket,指定服务器地址和端口
Socket socket = new Socket("localhost",8888);
//2、获取输出流,向服务器发送信息
OutputStream os = socket.getOutputStream();//字节输出流
PrintWriter pw = new PrintWriter(os);
pw.write("用户名:admin ; 密码:5555");
pw.flush();
socket.shutdownOutput();//关闭输出流
//3、接收服务器的响应信息
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String info = null;
while((info = br.readLine()) != null){
System.out.println("我是客户端,服务器端说:"+info);
}
br.close();
is.close();
pw.close();
os.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
第二步
package com.socket;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务器线程处理类
*/
public class ServerThread extends Thread {
//和本线程相关的Socket
Socket socket = null;
public ServerThread(Socket socket){
this.socket = socket;
}
//线程执行操作,响应客户端请求
public void run(){
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
OutputStream os = null;
PrintWriter pw = null;
try {
//3、获取输入流,并读取客户端信息
is = socket.getInputStream();
isr = new InputStreamReader(is);//将字节流包装为字符流
br = new BufferedReader(isr);//为输入流添加缓冲
String info = null;
while((info = br.readLine()) != null){
System.out.println("我是服务器,客户端说:" + info);
}
socket.shutdownInput();//关闭输入流
//4、获取输出流,响应客户端请求
os = socket.getOutputStream();
pw = new PrintWriter(os);//包装为打印流
pw.write("欢迎您,服务器接收到你信息。");
pw.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if ( pw != null)
pw.close();
if(os != null)
os.close();
if(br != null)
br.close();
if(isr != null)
isr.close();
if(is !=null)
is.close();
if(socket != null)
socket.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
第三步
package com.socket;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
public static void main(String[] arg){
try{
int count = 0;
//穿件服务器socket,绑定端口,并监听此端口
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("***服务器已启动,等待客户端连接***");
//循环监听等待客户端连接
while(true){
//调用accept()方法开始监听,等待客户端连接
Socket socket =serverSocket.accept();
//创建一个新的线程
ServerThread serverThread = new ServerThread(socket);
//启动线程
serverThread.start();
count++;
System.out.println("客户端的数量为:"+count);
}
}catch (IOException e){
e.printStackTrace();
}
}
}
---------------------
作者:Mark_XC
来源:CSDN
原文:https://blog.csdn.net/Mark_Chao/article/details/81007295
版权声明:本文为博主原创文章,转载请附上博文链接!
|
|