创建Socket
Socket socket = new Socket();
绑定一个socket到本地地址和端口上
socket.bind(new InetSocketAddress(Inet4Address.getLocalHost(),20001));
设置读取超时时间
socket.setSoTimeout(2000);
//是否复用未完全关闭的Socket地址,对于制定bind操作的套接字有效。(关闭连接后是否可以使用该端口号)
socket.setReuseAddress(true);
//是否开启Nagle算法。是否累积全部包后回送,有利于减少回送包
socket.setTcpNoDelay(true);
//是否需要在长时间无数据响应时发送确认数据(类似心跳包),时间大约2小时
socket.setKeepAlive(true);
//对于close关闭操作进行怎样的处理;默认为false,0
//false、0:默认情况,关闭时立即返回,底层系统接管输入流,将缓冲区内的数据发送完成
//true、0:关闭时立即返回,缓冲区数据抛弃,直接发送RST结束命令到对方,并无需经过2MSL等待
//true、200:关闭时最长阻塞200毫秒,随后按第二情况处理
socket.setSoLinger(true,200);
//是否让紧急数据内敛,默认false;紧急数据通过socket.sendUrgentData(1);发送
socket.setOOBInline(false);
//设置接收发送缓冲器大小
socket.setReceiveBufferSize(64*1024*1024);
socket.setSendBufferSize(64*1024*1024);
//设置性能参数:短链接,延迟,带宽的相对重要性 数字为权重
socket.setPerformancePreferences(1,1,1);
//连接到本地20000端口,超时时间3秒,超时则抛出超时异常
socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(),2000),3000);
客户端代码
//客户端代码
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
public class Client {
private static final int PORT = 20000;
private static final int LOCAL_PORT = 20001;
public static void main(String[] args) throws IOException{
Socket socket = createSocket();
initSocket(socket);
//连接到本地20000端口,超时时间3秒,超时则抛出超时异常
socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(),PORT),3000);
System.out.println("已发起服务器连接,并进入后续流程。。。");
System.out.println("客户端信息:" + socket.getLocalAddress() + " P:" + socket.getLocalPort());
System.out.println("服务器信息:" + socket.getInetAddress() + " P:" + socket.getPort());
try{
todo(socket);
}catch (Exception e){
System.out.println("异常关闭");
}
//释放资源
socket.close();
System.out.println("客户端已退出···");
}
private static void todo(Socket client) throws IOException {
//得到Socket输出流,并转换为打印流
OutputStream outputStream = client.getOutputStream();
//得到Socket输入流,并转换为BufferedReader
InputStream inputStream = client.getInputStream();
byte[] buffer = new byte[128];
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
byteBuffer.put((byte) 126);
char c = 'a';
byteBuffer.putChar(c);
int i = 2323216;
byteBuffer.putInt(i);
boolean b = true;
byteBuffer.put(b?(byte)1:(byte)0);
long l = 289756547;
byteBuffer.putLong(l);
float f = 45.145f;
byteBuffer.putFloat(f);
double d = 0.16348679846541;
byteBuffer.putDouble(d);
String str = "你好,lld!";
byteBuffer.put(str.getBytes());
//发送到服务器
outputStream.write(buffer,0,byteBuffer.position() + 1);
//接收服务器返回
int read = inputStream.read(buffer);
System.out.println("收到数据:" + read );
outputStream.close();
inputStream.close();
}
private static void initSocket(Socket socket) throws SocketException {
//设置读取超时时间
socket.setSoTimeout(2000);
//是否复用未完全关闭的Socket地址,对于制定bind操作的套接字有效。(关闭连接后是否可以使用该端口号)
socket.setReuseAddress(true);
//是否开启Nagle算法。是否累积全部包后回送,有利于减少回送包
socket.setTcpNoDelay(true);
//是否需要在长时间无数据响应时发送确认数据(类似心跳包),时间大约2小时
socket.setKeepAlive(true);
//对于close关闭操作进行怎样的处理;默认为false,0
//false、0:默认情况,关闭时立即返回,底层系统接管输入流,将缓冲区内的数据发送完成
//true、0:关闭时立即返回,缓冲区数据抛弃,直接发送RST结束命令到对方,并无需经过2MSL等待
//true、200:关闭时最长阻塞200毫秒,随后按第二情况处理
socket.setSoLinger(true,200);
//是否让紧急数据内敛,默认false;紧急数据通过socket.sendUrgentData(1);发送
socket.setOOBInline(false);
//设置接收发送缓冲器大小
socket.setReceiveBufferSize(64*1024*1024);
socket.setSendBufferSize(64*1024*1024);
//设置性能参数:短链接,延迟,带宽的相对重要性 数字为权重
socket.setPerformancePreferences(1,1,1);
}
private static Socket createSocket() throws IOException {
Socket socket = new Socket();
socket.bind(new InetSocketAddress(Inet4Address.getLocalHost(),LOCAL_PORT));
return socket;
}
}
服务器代码
import javax.naming.ldap.SortKey;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
public class Server {
private static final int PORT = 20000;
private static final int LOCAL_PORT = 20001;
public static void main(String[] args) throws IOException {
ServerSocket server = createServerSocket();
initServerSocket(server);
//绑定到本地端口上
server.bind(new InetSocketAddress(Inet4Address.getLocalHost(),PORT),50);
System.out.println("服务器准备就绪。。。");
System.out.println("服务器信息:" + server.getInetAddress() + " P:" + server.getLocalPort());
//等待客户端连接
for (;;){
//得到客户端连接
Socket client = server.accept();
//客户端构建异步线程
ClientHander clientHander = new ClientHander(client);
//启动线程
clientHander.start();
}
}
private static void initServerSocket(ServerSocket serverSocket) throws SocketException {
//是否复用未完全关闭的Socket地址(关闭连接后是否可以使用改端口号)
serverSocket.setReuseAddress(true);
//等效Socket#setReceiveBufferSize
serverSocket.setReceiveBufferSize(64*1024*1024);
//设置超时时间
// serverSocket.setSoTimeout(2000);
//设置性能
serverSocket.setPerformancePreferences(1,1,1);
}
private static ServerSocket createServerSocket() throws IOException {
ServerSocket socket = new ServerSocket();
return socket;
}
private static class ClientHander extends Thread{
private Socket socket;
public ClientHander(Socket socket) {
this.socket = socket;
}
@Override
public void run(){
super.run();
System.out.println("新客户端连接:" + socket.getInetAddress() + " P:" + socket.getPort());
try {
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[256];
int readCount = inputStream.read(buffer);
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer,0,readCount);
byte be = byteBuffer.get();
char c = byteBuffer.getChar();
int i = byteBuffer.getInt();
boolean b = byteBuffer.get() == 1;
long l = byteBuffer.getLong();
float f = byteBuffer.getFloat();
double d = byteBuffer.getDouble();
int pos = byteBuffer.position();
String str = new String(buffer, pos,readCount-pos-1);
System.out.println("收到数量:" + readCount + "\n数据: \n"
+ be + "\n"
+ c + "\n"
+ i + "\n"
+ b + "\n"
+ l + "\n"
+ f + "\n"
+ d + "\n"
+ str + "\n");
outputStream.write(buffer,0,readCount);
outputStream.close();
outputStream.close();
}catch (Exception e){
System.out.println("连接异常断开");
}finally {
//连接关闭
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("客户端已退出:" + socket.getInetAddress() + " P:" + socket.getPort());
}
}
}