服务端demo:
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Test {
public static void main(String[] args) {
try {
ServerSocket socket = new ServerSocket(9999);//创建套接字、配置端口号为9999,IP地址默认为本机地址
System.out.println("创建套接字成功");
while(true){
final Socket con = socket.accept();//等待客户端连接
System.out.println("accept连接成功");
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
int len;
byte[] data = new byte[128];
try {
InputStream in;
in = con.getInputStream();
len = in.read(data);
System.out.println(new String(data, 0, len));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
服务端demo:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Socket socket;
try {
int len;
byte[] massge = new byte[128];
socket = new Socket("192.168.183.1", 1111);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
Scanner sc = new Scanner(System.in);
String data = sc.next();
out.write(data.getBytes());
len = in.read(massge);
System.out.println(new String(massge, 0, len));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}