基于TCP协议的Socket网络编程 单向通信(客户端与服务端建立连接)
项目结构:
1.新建clientProject客户端工程
2.新建客户端Test类
3.新建serverProject客户端工程
4.新建服务器端Test类
项目代码:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Test {
public static void main(String[] args) throws IOException {
//1.创建Socket对象
Socket client=new Socket("192.168.41.42",9999);
//2.获取输出流
OutputStream os=client.getOutputStream();
os.write('f');
//3.获取输入流
InputStream is=client.getInputStream();
byte[] buf=new byte[1024];//中转站
int len=0;//读到的字节个数
while((is.read(buf))!=-1){
System.out.println(new String(buf,0,len));
}
//4.关闭流
if(is!=null){
is.close();
}
if(os!=null){
os.close();
}
if(client!=null){
client.close();
}
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/*
* 基于TCP协议的Socket网络编程 单向通信(客户端与服务端建立连接)
* */
public class Test {
public static void main(String[] args) throws IOException {
System.out.println("=========-----服务器已启动-------===");
//1.创建ServerSocket对象
ServerSocket server=new ServerSocket(9999);
//2.监听是否有客户端来请求连接
Socket client=server.accept();
//3.获取输入流
InputStream is=client.getInputStream();
System.out.println((char)is.read());
//4.获取输出流
OutputStream os=client.getOutputStream();
os.write("收到了!".getBytes());
//5.关闭流,关闭Socket
if(os!=null){
os.close();
}
if(is!=null){
is.close();
}
if(client!=null){
client.close();
}
}
}
运行结果:连接建立成功!