TCP Socket

例  客户端如何连接服务器

public class TestTCPServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(6666);//要指明服务器的端口号
Socket s = ss.accept();//s指服务器与这一个客户端的Socket连接
System.out.println("A Client Connect!");
}
}


public class TestTCPClient {

public static void main(String[] args) throws Exception {
Socket s = new Socket("127.0.0.1",6666);//指明服务器的IP地址和端口号
}

}


先运行Server,再运行Client。

Server Console

A Client Connect!


服务器程序往往是和客户端程序一起开发的。


客户端现在已经连接上了服务器,那如何通信呢?

使用流!


例  客户端向服务器发送消息

public class TestTCPServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(6666);
Socket s = ss.accept();//不停的处于接收状态
System.out.println("A Client Connect!");

//一个Socket包含了两个管道,一个输入一个输出。
//拿到输入管道,定义为DataInputStream类型
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readUTF());
dis.close();
s.close();
}
}


public class TestTCPClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("127.0.0.1",6666);
//通过getOutputStream()来拿到输出管道,并定义为DataOutputStream类型
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
Thread.sleep(5000);//使当前线程睡5s,以实验readUTF()是否阻塞,是否等待。
dos.writeUTF("Hello Server.");
dos.flush();//刷新输出流
dos.close();
s.close();
}
}

先运行Server,再运行Client。

Server Console

A Client Connect!
Hello Server.


其中,ss.accept()和readUTF()都是阻塞式的,如果没有数据来,就一直死死等着。

并不是读不到东西就往下运行。

但是线程就被堵住了。


例  服务器向客户端发送消息

public class TestTCPServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(6666);
Socket s = ss.accept();
System.out.println("A Client Connect!");

DataOutputStream dos = new DataOutputStream(s.getOutputStream());

//.getInetAddress()可以拿到客户端的IP地址,.getPort()拿到客户端端口号。
dos.writeUTF("Hello," + s.getInetAddress() + " port#" + s.getPort() + ".");
dos.close();
s.close();
}
}


public class TestTCPClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("127.0.0.1",6666);
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readUTF());
dis.close();
s.close();
}
}

Client Console

Hello,/127.0.0.1 port#2094.




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值