实现了基于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();
}
}
}