TCP编程1:客户端和服务器端的创建

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;


import org.junit.Test;


public class TestTCP1 {
/*
* 客户端
*/
@Test
public void client() {
OutputStream os = null;
try {
// 1.创建一个Socket的对象,通过构造器指明服务器端的IP地址,以及其接收程序的端口号
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
// 2.getOutputStream():发送数据,方法返回OutputStream的对象
os = socket.getOutputStream();
// 3.具体的输出过程
os.write("我是服务器端".getBytes());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.关闭流
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


/*
* 服务器端
*/
@Test
public void server() {
ServerSocket ss = null;
Socket s = null;
InputStream is = null;
try {
//1.创建一个ServerSocket的对象,通过构造器指明自身的端口号
ss = new ServerSocket(9090);
//2.调用accept()方法,返回一个Socket的对象
s = ss.accept();
//3.调用Socket对象的getInputStream()方法获取从客户端发送过来的输入流
is = s.getInputStream();
//4.对获取的流进行操作
byte[] b = new byte[1024];
int len;
while ((len = is.read(b)) != -1) {
String str = new String(b, 0, len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//5.关闭流以及Socket、ServerSocket的对象
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (s != null) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值