Socket编程学习

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;/*** 描述:** @Author 皮丘的神圣殿堂* @Date 2020/9/23 13:19*/
public class TCPTest1 {@Testpublic void client() {Socket socket = null;OutputStream os = null;try {//1.创建socket对象,指明服务器端的端口号-socket和IP-InetAddressInetAddress ia = InetAddress.getByName("127.0.0.1");socket = new Socket(ia, 8899);//2.获取输出流os = socket.getOutputStream();//3.写出数据os.write("你好,我是客户端".getBytes());} catch (IOException e) {e.printStackTrace();} finally {//4.关闭流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 {//1.创建socket服务器端,知名自己的端口号ss = new ServerSocket(8899);//2.表明可以接收来自客户端的socketsocket = ss.accept();//3.获取输入流is = socket.getInputStream();//4.读取输入流的数据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 {//5.关闭操作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();}}}
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部