服务端,运行时要先启动
package net.tcp;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerDemo {
public static void main(String[] args) throws IOException {
//通过server对象创建服务端,必须对外提供一个端口,否则客户端无法连接
ServerSocket ss = new ServerSocket(10002);
//获取客户端连接对象
Socket s = ss.accept(); //阻塞式
String ip = s.getInetAddress().getHostAddress();
//读取客户端输入流
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
String text = new String(buf,0,len);
System.out.println("server...");
System.out.println(ip+":"+text);
s.close();
ss.close();
}
}
客户端
package net.tcp;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientDemo {
public static void main(String[] args) throws UnknownHostException, IOException {
//tcp 客户端,使用socket对象,建议一创建就明确目的地
//自己的ip地址
Socket socket = new Socket("10.1.35.73",10002);
//获取socket中的输出流
OutputStream out = socket.getOutputStream();
out.write("i come tcp".getBytes());
//只关这个就行了
socket.close();
}
}