socket通信编程代码java
时间: 2024-05-09 13:13:35 浏览: 105
socket通信java编程
Socket编程是一种基于TCP/IP协议的网络编程,它是实现网络通信的一种方式。在Java中,Socket编程可以使用Java的标准库java.net包来实现。下面是一个简单的Socket通信的代码示例:
服务端代码:
```java
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(12345);
} catch (IOException e) {
System.err.println("Could not listen on port: 12345.");
System.exit(1);
}
Socket clientSocket = null;
try {
System.out.println("Waiting for connection.....");
clientSocket = serverSocket.accept();
System.out.println("Accepted connection : " + clientSocket);
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
String inputLine, outputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Server: " + inputLine);
out.println(inputLine);
if (inputLine.equals("Bye.")) {
break;
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
```
客户端代码:
```java
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("localhost", 12345);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: localhost.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("Client: " + userInput);
System.out.println("Server: " + in.readLine());
if (userInput.equals("Bye.")) {
break;
}
}
out.close();
in.close();
stdIn.close();
socket.close();
}
}
```
以上代码实现了一个简单的客户端和服务端之间的通信。运行服务端程序后,再运行客户端程序,输入内容并回车,即可在客户端和服务端之间实现通信。
阅读全文