TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
1,首先写服务器端的程序,设置监听的端口,当客户端连接到这个端口时就向其发送数据
package com.zhangjie.socket;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServer {
public static void main(String[] args) {
//在8888端口监听
ServerSocket s;
try {
s = new ServerSocket(8888);
while(true){
Socket s1 = s.accept();
OutputStream os = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("hello,"+s1.getInetAddress()+"port#"+s1.getPort()+" bye-bye");
dos.close();
s1.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2,在客户端接收数据
package com.zhangjie.socket;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
/*
* 要点
* 1,Java Socket编程步骤
* 2,Socket/ServerSocket类用法
* 3,通过Socket对象可以获取通信对方Socket的信息
*/
public class TestClient {
public static void main(String[] args) {
try{
//从服务器的8888端口接收数据
Socket s1 = new Socket("127.0.0.1",8888);
InputStream is = s1.getInputStream();
DataInputStream dis = new DataInputStream(is);
System.out.println(dis.readUTF());
}catch(ConnectException connE){
connE.printStackTrace();
System.out.println("服务器连接失败");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在客户端接收到的数据打印到控制台为:
hello,/127.0.0.1port#4009 bye-bye
注:4009为客户端的端口 |
|