實現了基於TCP的Java Socket編程,功能很簡單:客戶端向服務器端輸出一名話"connect",服務器端接收輸出到控制台並向客戶端輸出一名話"Hello",客戶端接收並輸出。
1.服務器端
代碼如下:
package javase.net.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 TCPServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
// 讀取客戶端數據
InputStream info = socket.getInputStream();
DataInputStream dis = new DataInputStream(info);
System.out.println(dis.readUTF());
// 向客戶端輸出數據
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("Hello!");
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.客戶端:
代碼如下:
package javase.net.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 TCPClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("192.168.1.123", 8888);
// 向服務器端發送數據
OutputStream os = socket.getOutputStream();
DataOutputStream bos = new DataOutputStream(os);
bos.writeUTF("Connect");
bos.flush();
// 接收服務器端數據
InputStream is = socket.getInputStream();
DataInputStream dis = new DataInputStream(is);
System.out.println(dis.readUTF());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}