1. 示例:
package edu.learn.foundation;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpUtil {
ServerSocket serverSocket;
Socket socket;
BufferedReader bufferedReader;
public void setServer(){
try {
serverSocket=new ServerSocket(8991);
socket = serverSocket.accept();
System.out.println("套接字创建成功");
System.out.println("等待客户机连接....");
InputStream inputStream= socket.getInputStream();
InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
bufferedReader= new BufferedReader(inputStreamReader);
this.getClientMessage(bufferedReader);
try {
if(bufferedReader!=null){
bufferedReader.close();
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
private void getClientMessage(BufferedReader bufferedReader){
try {
while (true) {
String getString=bufferedReader.readLine();
if(getString==null)
return;
System.out.println(getString);
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
public static void main(String[] args){
TcpUtil serverUtil = new TcpUtil();
serverUtil.setServer();
}
}
package edu.learn.foundation;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.Socket;
public class ClientUtil {
Socket socket;
PrintWriter printWriter;
public void SetClient(){
System.out.println("开始连接。。。。");
try {
socket = new Socket("127.0.0.1", 8991);
OutputStream outputStream = socket.getOutputStream();
printWriter= new PrintWriter(outputStream);
printWriter.println("hello world");
printWriter.flush();
System.out.println("完成连接。。。。");
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
printWriter.close();
try {
socket.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
ClientUtil clientUtil = new ClientUtil();
clientUtil.SetClient();
}
}