内容
JAVA使用socket实现客户端与服务端的通信、多线程服务端
一、Demo
1. Server服务器端
public class socketServer {
//定义端口号,服务端与客户端一致,自己定义不冲突即可
public static final int PORT=8888;
public static void main(String[] args) throws IOException{
//建立ServerSocket
ServerSocket server = new ServerSocket(PORT);
System.out.println("ServerSocket:" + server );
try{
/*程序阻塞,等待连接。即直到有一个客户请求到达,程序方能继续执行*/
//接收客户端连接
Socket socket = server .accept();
System.out.println("Socket accept:"+socket);
try {
//连接成功,建立相应的I/O数据流
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//在循环中,与客户机通信
while(true){
String str=in.readUTF(); //从客户机中读数据
if(str.equals("end"))break; //当读到end时,程序终止(客户端发送end作为结束标志)
System.out.println(str);
out.writeUTF("Echoing:"+str); //向客户机中写数据
}
in.close();
out.close();
}finally{
socket.close();
}
}finally{
server.close();
}
}
}
2. Client客户端
public class socketClient {
public static void main(String[] args) throws IOException{
//建立Socket,服务器在本机的8888端口处进行“侦听”
//服务器的ip地址可在服务器端cmd窗口通过ipconfig查看
Socket socket = new Socket("-填写服务端的IP地址-",8888);
System.out.println("Socket:"+socket );
try{
//套接字建立成功,建立I/O流进行通信
DataInputStream in=new DataInputStream(ss.getInputStream());
DataOutputStream out=new DataOutputStream(ss.getOutputStream());
for(int i=0;i<6;i++){
dos.writeUTF("测试:"+i); //向服out务器发数据
dos.flush(); //刷新输出缓冲区,以便立即发送
System.out.println(dis.readUTF()); //将从服务器接收的数据输出
}
out.writeUTF("end"); //向服务器发送终止标志
out.flush(); //刷新输出缓冲区,以便立即发送
out.close();
in.close();
}finally{
socket.close();
}
}
}
二、服务器多线程接受多个客户端
1.Srever改变
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class socketClientThreads implements Runnable {
public static final int PORT=8888;
Socket socket;
socketClientThreads(Socket ssocket){
this.socket = ssocket;
}
public static void main(String[] args) throws IOException {
ServerSocket socketServer=new ServerSocket(PORT);
System.out.println("ServerSocket:"+socketServer);
try{
//服务器长运行
while(true){
System.out.println("wait..");
Socket socket_ = socketServer.accept();
System.out.println("Socket accept: " + socket_);
//接受一个client创建一个线程
new Thread( new socketClientThreads(socket_) ).start();
}
}finally {
socketServer.close();
}
}
@Override
public void run() {
try {
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
System.out.println("多线程创建:");
while(true) {
String str=in.readUTF();
if(str.equals("end")) {
break;
}
System.out.println(str);
out.writeUTF("Echoing:"+str);
}
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端与上面相同即可