简单的发送和接收
package sock;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MyTcp {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", 12345);
OutputStream out = socket.getOutputStream();
out.write("我来了tcp".getBytes());
socket.close();
}
}
class Ser{
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(12345);
Socket socket = ss.accept();
System.out.println(socket.getInetAddress().getHostAddress());
InputStream in = socket.getInputStream();
byte[] arr = new byte[1234];
int read = in.read(arr);
System.out.println(new String(arr,0,read));
socket.close();
ss.close();
}
}
添加一次应答。
package sock;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MyTcp2 {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", 12333);
OutputStream out = socket.getOutputStream();
out.write("我又来了,哈哈".getBytes());
InputStream in = socket.getInputStream();
byte[] arr = new byte[1234];
int num = in.read(arr);//这个方法是阻塞的等待录入。
System.out.println(new String(arr,0,num));
socket.close();
}
}
class MySer2{
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(12333);
Socket socket = ss.accept();
System.out.println(socket.getInetAddress().getHostAddress());
InputStream in = socket.getInputStream();
byte[] arr = new byte[1234];
int num = in.read(arr);
System.out.println(new String(arr,0,num
));
OutputStream out = socket.getOutputStream();
Thread.sleep(10*1000);
out.write("我也又收到了,你收到了吗?".getBytes());
socket.close();
ss.close();
}
}