服务端:
客户端:
public class ServerSide {
public void service() {
ServerSocket server = null;
Socket client = null;
BufferedReader is = null;
PrintWriter os = null;
try {
server = new ServerSocket(2046);
System.out.println("服务器启动...");
client = server.accept();
is = new BufferedReader(new InputStreamReader(client
.getInputStream()));
os = new PrintWriter(client.getOutputStream());
String msg = null;
// 接受客户端消息,当客户端断掉返回null,否则一直等待消息
while ((msg = is.readLine()) != null) {
System.out.println("客户端说:" + msg);
// 客户端使用readline,这里不能使用print
os.println("服务端收到消息");
os.flush();
if (msg.equals("end"))
break;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
if (client != null) {
client.close();
}
if (server != null) {
server.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ServerSide().service();
}
}
客户端:
public class ClientSide {
public void service() {
Socket socket = null;
BufferedReader is = null;
BufferedReader input = null;
PrintWriter os = null;
try {
socket = new Socket("localhost", 2046);
is = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
os = new PrintWriter(socket.getOutputStream());
input = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String msg = input.readLine();
os.println(msg);
os.flush();
if (msg.equals("end"))
break;
System.out.println(is.readLine());
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ClientSide().service();
}
}