JAVA信息传送代码之发送信息
发送信息代码参考
package xin.week1.day1;
import org.junit.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;
import java.net.UnknownHostException;
//客户端向服务端发送消息
public class tcpwenbeng {
@Test
public void server(){
ByteArrayOutputStream baos = null;
InputStream inputStream =null;
Socket accept = null;
try {
//1.创建一个serverSocket对象,并指定端口号
ServerSocket ss = new ServerSocket(8099);
//2.让socket处于监听状态
accept = ss.accept();
//3.通过socket对象获取输入流
inputStream = accept.getInputStream();
//4.定义输出流去读取内容
baos =new ByteArrayOutputStream();
//5.定义输出流去读取内容
byte[] bytes = new byte[1024];
int len;
//6.读取内容
while ((len=inputStream.read(bytes))!=-1){
baos.write(bytes,0,len);
}
System.out.println(baos.toString());
System.out.println("收到来自"+ss.getInetAddress().getHostAddress());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (baos!=null){
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (accept!=null){
try {
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void client(){
Socket socket=null;
OutputStream os=null;
try {
//1.获取主机地址
InetAddress host = InetAddress.getLocalHost();
//2.获取套接字对象
socket = new Socket(host,8099);
//3.通过套接字对象获取输出流向服务端发送数据
os = socket.getOutputStream();
//4.定义发送的内容
os.write("你好,服务端".getBytes());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//5.关闭流
if (socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
在这里欢迎大家的点赞、关注、评论,以此来促进大家互相学习交流,同时可以让新加入的小伙伴更快的了解新知识!!!
文章内容如有侵权,请联系作者进行删除
≧◠◡◠≦ 1分2分都是爱,感谢已经打赏的老板,和正在打赏的老板们 ≧◠◡◠≦