简单Socket

服务端:

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();
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值