import org.junit.jupiter.api.Test;import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPTest1 {@Testpublic void client() {Socket socket = null;OutputStream os = null;try {InetAddress ia = InetAddress.getByName("127.0.0.1");socket = new Socket(ia, 8899);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();}}}}@Testpublic void server() {ServerSocket ss = null;Socket socket = null;InputStream is = null;ByteArrayOutputStream baos = null;try {ss = new ServerSocket(8899);socket = ss.accept();is = socket.getInputStream();baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len;while ((len = is.read(buffer)) != -1) {baos.write(buffer, 0, len);}System.out.println(baos.toString());} catch (IOException e) {e.printStackTrace();} finally {try {if (baos != null) {baos.close();}} catch (IOException e) {e.printStackTrace();}try {if (is != null) {is.close();}} catch (IOException e) {e.printStackTrace();}try {if (socket != null) {socket.close();}} catch (IOException e) {e.printStackTrace();}try {if (ss != null) {ss.close();}} catch (IOException e) {e.printStackTrace();}}}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!