标签:generated .so and 需要 address tput pac rate 实现
客户端向服务器端发送消息,服务器端给客户端反馈消息。代码和上一篇的代码差不多。
package com.demo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
/**
*
* @author Lynn
* 使用Socket类实现TCP协议; Socket常用的构造方法:Socket(InetAddress address, int
* port)和 Socket(String host, int port) 客户端给服务端发送信息,服务端输出此信息到控制台上;
*
*/
public class Demo02 {
// 客户端;
public static void main(String[] args) {
InetAddress inet;
Socket socket = null;
OutputStream out = null;
InputStream in = null;
try {
inet = InetAddress.getLocalHost();
//这里填写服务器端的ip和端口号;
socket = new Socket(inet, 6868);
out = socket.getOutputStream();
out.write("我是客户端".getBytes());
//必须要主动关闭,否则无法收到服务器端的回复。这里告诉服务器端数据已经发送完了,这里其实就是客户端单方面关闭了输出流,告诉服务器端这次要发送的消息已经发送完毕,具体可以看附;
socket.shutdownOutput();
in = socket.getInputStream();
int len;
byte[] content = new byte[20];
while((len=in.read(content))!=-1) {
String str = new String(content,0,len);
System.out.println("客户端收到服务器的回复:"+str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(out!=null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(socket!=null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
package com.demo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Demo03 {
// 服务器端;
public static void main(String[] args){
//端口号;
ServerSocket serverSocket=null;
Socket socket =null;
InputStream in = null;
OutputStream out = null;
try {
serverSocket = new ServerSocket(6868);
socket = serverSocket.accept();
in = socket.getInputStream();
byte[] content = new byte[20];
int length;//记录真正数据的长度;
while ((length = in.read(content)) != -1) {
String str = new String(content, 0, length);
System.out.println("服务器端收到客户端的请求:"+str);
}
out = socket.getOutputStream();
out.write("我收到了你的消息".getBytes());
//这里不需要shutdownOutput程序可以正常结束,猜测是因为最后会执行out.close(),导致Socket关闭,客户端可以自行结束。
//out.shutdownOutput();
} catch (Exception e) {
// TODO: handle exception
}finally {
if(out!=null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(in!=null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(socket!=null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(serverSocket!=null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
关于socket中的shutdownOutput()shutdownIntput()方法分析https://blog.csdn.net/zhuoni2013/article/details/56494681
标签:generated .so and 需要 address tput pac rate 实现
原文地址:https://www.cnblogs.com/SnailsRunning/p/10123694.html