直接上代码:
服务器端:
import java.net.Socket;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.net.ServerSocket;
public class ServerSide {
private static Logger log = Logger.getLogger(ServerSide.class);
public static void serverStart() {
ServerSocket server = null;
try {
// 创建好监听器
server = new ServerSocket(9527);
log.info("服务器启动==========");
System.out.println("服务器启动==========");
while (true) {
Socket sc = server.accept();// 进入阻塞状态,直到接收到发送发消息,返回给我们一个Socket
log.info("服务器接收消息==========");
System.out.println("服务器接收消息==========");
// 开启线程处理socket
new MsgThread(sc);
}
} catch (IOException e) {
log.error("Server io error");
} finally {
IOUtils.close(server);
}
}
public static void main(String[] args) {
serverStart();
}
}
客户端:
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class MsgClient {
public static void msgClient() {
// 端口号
int port = 9527;
String ip = "127.0.0.1";
String msg = "你好,我是客户端!";
// 发送方Socket操作
Socket socket = null;
try {
socket = new Socket(ip, port);// 开启Socket链接
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write(msg);
bw.flush();
} catch (UnknownHostException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();// 关闭Socket
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
msgClient();
}
}
消息处理线程:
import java.net.Socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MsgThread extends Thread{
private Socket sc;
public MsgThread(Socket sc) {
this.sc = sc;
this.start();
}
@Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(sc.getInputStream()));
String msg = br.readLine();
System.out.println(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
IOUtils.close(sc);
}
}
}
IOUtils类:
import org.apache.log4j.Logger;
import java.io.Closeable;
import java.io.IOException;
/**
* 关闭系统资源
*
* @author: lx
* @date: 2018/3/16
*/
public class IOUtils {
private static Logger log = Logger.getLogger(IOUtils.class);
public static void close(Closeable... closeables) {
for (Closeable c : closeables) {
if (c != null) {
try {
c.close();
} catch (IOException e) {
if (log != null) {
log.warn("Exception in closing " + c, e);
}
}
}
}
}
}
测试:分别启用服务器端的main方法和客户端的main方法
服务器启动==========
服务器接收消息==========
你好,我是客户端!