1.服务端
1.1服务端代码
package com.cn.lixv;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.Buffer;
public class study1 {
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
try {
serverSocket = new ServerSocket(9999);
socket = serverSocket.accept();
is = socket.getInputStream();
byte[] buffer = new byte[1024];
int len;
String msg = "";
while ((len = is.read(buffer)) != -1) {
msg = new String(buffer, 0, len);
}
System.out.println(msg);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
1.2服务端代码讲解
ServerSocket
类以端口作为参数,在本机创建一个服务。ServerSocket
的accept()
方法返回一个Socket类,用于接收客户端的连接。Socket
的getInputStream()
方法用于接收客服端的输出流。
2.客户端
2.1客户端代码
package com.cn.lixv;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class study {
public static void main(String[] args) {
InetAddress serverIP = null;
Socket socket = null;
OutputStream os = null;
try {
serverIP = InetAddress.getByName("127.0.0.1");
socket = new Socket(serverIP,9999);
os = socket.getOutputStream();
os.write("你好,".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
2.2客户端代码讲解
InetAddress
用于存放服务器的ip。Socket
通过服务器的ip和端口建立一个连接。Socket
的getOutputStream()
方法用于向服务端发送输出流。