Java网络编程实现多客户端连接服务器
程序员文章站
2024-03-23 09:39:58
...
使用多线程实现多客户端连接服务器,
客户端代码如下:
/**
* Socket客户端
* 功能为:发送字符串nihao到服务器端,并打印出服务器端的返回信息
*/
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class SocketClient {
public static void main(String[] args) {
Socket socket = null;
InputStream is = null;
OutputStream os = null;
// 服务器IP
String serverIP = "127.0.0.1";
// 服务器端口
int port = 8080;
try {
// 建立连接
socket = new Socket(serverIP, port);
is = socket.getInputStream();
os = socket.getOutputStream();
//发送信息
os.write("nihao".getBytes());
//接收信息
byte[] buffer = new byte[1024];
int n = is.read(buffer);
// 输出返回信息
System.out.println("接收服务器信息:" + new String(buffer, 0, n));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//关闭流和连接
is.close();
os.close();
socket.close();
} catch (Exception e2) {
}
}
}
}
服务器端代码如下:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
public class ClientHandler implements Runnable {
Socket socket = null;
InputStream inputStream = null;
OutputStream outputStream = null;
public ClientHandler(Socket socket) {
this.socket = socket;
}
public void run() {
byte[] buffer = new byte[1024];
//读取数据
int length;
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
length = inputStream.read(buffer);
System.out.println(new String(buffer,0,length));
outputStream.write("niyehao".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
inputStream.close();
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args){
new SocketServer().StartServer();
}
public void StartServer(){
ServerSocket serverSocket = null;
Socket socket = null;
int port=5555;
try{
serverSocket = new ServerSocket(port);
System.out.println("server start");
while(true){
socket = serverSocket.accept();
System.out.println("client connectioned,IP:"+socket.getInetAddress());
Thread t = new Thread(new ClientHandler(socket));
t.start();
}
}catch(IOException e){
e.printStackTrace();
} finally{
}
}
}
推荐阅读
-
Java网络编程实现多客户端连接服务器
-
Java网络编程一个基础案例分析,基于TCP协议的客户端上传文件给服务器端(单线程版)
-
Linux网络编程之简单TCP客户端服务器端实现
-
JAVA TCP网络编程(客户端和服务器端的代码)
-
JAVA网络编程-TCP客户端与服务器端连接
-
java 利用TCP协议从客户端向服务器端发送文件.(网络编程)
-
java网络编程之服务器同时处理多个客户端示例
-
【TCP/IP网络编程实验】之【python实现客户端给服务器发送小写字母,服务器返回大写字母(UDP)】
-
【TCP/IP网络编程实验】之【python实现客户端给服务器发送小写字母,服务器返回大写字母(TCP)】
-
简单讲解Java的Socket网络编程的多播与广播实现