TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
1,服务器端发送数据并接受数据
package com.zhangjie.socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TestSocketServer {
public static void main(String[] args) {
InputStream in = null;
OutputStream out = null;
try{
ServerSocket ss = new ServerSocket(5888);
Socket socket = ss.accept();
//从客户端获取输入流和输出流
in = socket.getInputStream();
out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
DataInputStream dis = new DataInputStream(in);
String s = null;
//如果接收的客户端的输入内容不为空
if((s=dis.readUTF()) != null){
System.out.println(s);
System.out.println("from:"+socket.getInetAddress());
System.out.println("from:"+socket.getPort());
}
dos.writeUTF("hi,hello");
dis.close();
dos.close();
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
2,客户端发送并接收数据
package com.zhangjie.socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class TestSocketClient {
public static void main(String[] args) {
InputStream is = null;
OutputStream os = null;
try{
Socket socket = new Socket("localhost",5888);
is = socket.getInputStream();
os = socket.getOutputStream();
DataInputStream dis = new DataInputStream(is);
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("hey");
String s = null;
if((s=dis.readUTF()) != null){
System.out.println(s);
}
dos.close();
dis.close();
socket.close();
}catch(UnknownHostException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
|