客户端代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClient {
public static void main(String[] args) {
// 声明一个socket
Socket socket = null;
try {
String msg = null;
// 产生socket对象,制定服务器地址和服务器监听的端口号
socket = new Socket("127.0.0.1", 8080);
// 从标准输入(键盘)读取内容,获取socket的输出流,将读取到的内容放入输出流中
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
OutputStream outputStream = socket.getOutputStream();
while (!(msg = reader.readLine()).equalsIgnoreCase("exit")) {
outputStream.write(msg.getBytes());
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
服务器端代码:
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public static void main(String[] args) {
// 声明一个服务器端socket
ServerSocket serverSocket = null;
// 声明一个socket来接受客户端连接
Socket socket = null;
try {
int temp;
// 定义服务器端socket并指定监听端口
serverSocket = new ServerSocket(8080);
// 调用阻塞式方法来获取客户端连接的socket
socket = serverSocket.accept();
// 获取客户端socket的输入流
InputStream inputStream = socket.getInputStream();
// 读取客户端socket的输入流的内容并输出
byte[] buffer = new byte[512];
while ((temp = inputStream.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, temp));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
转载于:https://blog.51cto.com/4949301/1210599