接收
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Tcp {
public static void main(String[] args) throws Exception{
try {
System.out.println("12345678");
int port = 8081;
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
Socket socket = serverSocket.accept();
OutputStream output = socket.getOutputStream();
InputStream input = socket.getInputStream();
String IP = serverSocket.getInetAddress().getHostAddress();
System.out.println(IP + "......connected");
int i = 0;
while (socket.isConnected()) {
byte[] b = new byte[1024];
int len = input.read(b) + 1;
String str = new String(b, 0, len);
System.out.println("数据为" + str);
output.write(str.getBytes());
i++;
if(i > 10) {
break;
}
}
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
发送
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpSend {
public static void main(String[] args) throws Exception {
BufferedReader buff=null;
InetAddress serverip=null;
int serverport=38700;
Socket client=null;
OutputStream out=null;
String info=null;
serverip=InetAddress.getByName("454585x8l0.qicp.vip");
System.out.println("接收方: " + serverip.getHostName());
System.out.println("接收IP: " + serverip.getHostAddress());
client=new Socket(serverip,serverport);
out=client.getOutputStream();
for(int i=0;i<5;i++) {
System.out.println("请输入发送的数据");
buff=new BufferedReader(new InputStreamReader(System.in));
info=buff.readLine();
out.write(info.getBytes());
}
out.close();
buff.close();
client.close();
}
}