Java实现Socket通信

用到的知识:
IO流
Socket
先建立好客户端,将要发送的数据转为字符流加载到缓冲区
Client.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.ifueen.classtest.socket;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {
private Socket sk;
public static void main(String[] args) {
Client client = new Client();
client.connect();
}

/**
* 创建客户端并连接到服务器
*/
public void connect() {

try {
sk = new Socket("localhost",8088);
System.out.println("创建客户端成功");
//拿到自身的输出流
OutputStream outputStream = sk.getOutputStream();
//将字节流转换为字符流
OutputStreamWriter writer = new OutputStreamWriter(outputStream, "utf-8");
//创建缓冲区
PrintWriter pw = new PrintWriter(writer,true);
pw.println("会沉寂吗");

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

然后将服务端搭好:Server.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.ifueen.classtest.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

private ServerSocket ss;

public static void main(String[] args) {
// TODO Auto-generated method stub
Server server = new Server();
server.connect();
server.strat();
}

/**
* 服务端开启
*/
public void connect(){
try {
//创建服务端的端口
ss = new ServerSocket(8088);
System.out.println("服务端初始化成功");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* 启动监听
*/
public void strat() {

try {
//拿到客户端
Socket accept = ss.accept();
//获取客户端的ip地址
String address = accept.getInetAddress().getHostAddress();
System.out.println("客户端ip为:"+address);

//拿到客户端传递的字节流
InputStream is = accept.getInputStream();
//将字节流转换为字符流
InputStreamReader ins = new InputStreamReader(is,"utf-8");
//创建输入的缓冲区
BufferedReader rd = new BufferedReader(ins);
//读取一行
String message = rd.readLine();
System.out.println(address+":"+message);


} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}




}

先启动服务端,然后再启动客户端,连接好后便可以将客户端的数据发送给服务端了

❤赏点钱让我买杯快乐水8❤