JAVA 服务端和客户端Socket通信的简单例子
程序员文章站
2022-04-24 13:26:17
...
服务端:
package socketTest;
import java.net.*;
import java.io.*;
public class GreetingSocket {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(6066);
while (true) {
//wait Client connect
Socket client = serverSocket.accept();
//get Client message
DataInputStream input = new DataInputStream(client.getInputStream());
String clientInputStr = input.readUTF();
System.out.println(clientInputStr);
//send Client message
DataOutputStream output = new DataOutputStream(client.getOutputStream());
String clientOutputStr = "Server";
output.writeUTF(clientOutputStr);
//close input output
input.close();
output.close();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
客户端:
package socketTest;
import java.io.*;
import java.net.*;
public class ClientSocket {
public static void main(String[] args) {
Socket socket = null;
while (true) {
try {
//connect Server
socket = new Socket("localhost", 6066);
//send Server message
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
out.writeUTF(str);
//get Server message
DataInputStream input = new DataInputStream(socket.getInputStream());
String serverInputStr = input.readUTF();
System.out.println(serverInputStr);
//close output input
out.close();
input.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}
上一篇: Python语言描述连续子数组的最大和
下一篇: Flash怎么制作歌词逐渐消失的动画?