try {
ServerSocket serverSocket = new ServerSocket(9000);//建立端口号为9000
Socket socket = serverSocket.accept();//等待客户端的连接
InputStream is = socket.getInputStream();//接受客户端的信息流
//接受信息代码模块
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1)
{
String msg = new String(buffer, 0, len);
System.out.println(msg);
}
} catch (IOException e) {
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) { try { ServerSocket serverSocket = new ServerSocket(9000);//建立端口号为9000 Socket socket = serverSocket.accept();//等待客户端的连接 InputStream is = socket.getInputStream();//接受客户端的信息流 //接受信息代码模块 byte[] buffer = new byte[1024]; int len; while ((len=is.read(buffer))!=-1) { String msg = new String(buffer, 0, len); System.out.println(msg); } } catch (IOException e) { e.printStackTrace(); } } }客户端:
public class TcpClient { public static void main(String[] args) { try { InetAddress byName = InetAddress.getByName("127.0.0.1");//ip地址 int port=9000;//端口号 Socket socket = new Socket(byName, port);//建立一个socket连接 OutputStream ou = socket.getOutputStream();//发送io流 ou.write("你好,李焕英".getBytes(StandardCharsets.UTF_8));//getBytes()是将String字符串转换为Byte数组 } catch (Exception e) { e.printStackTrace(); } } }
import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; //客户端 public class TcpClient { public static void main(String[] args) { try { InetAddress byName = InetAddress.getByName("127.0.0.1");//ip地址 int port=9000;//端口号 Socket socket = new Socket(byName, port);//建立一个socket连接 OutputStream ou = socket.getOutputStream();//发送io流 ou.write("你好,李焕英".getBytes(StandardCharsets.UTF_8));//getBytes()是将String字符串转换为Byte数组 } catch (Exception e) { e.printStackTrace(); } } }
先运行服务器端,再运行客户端,运行结果如下:
S:javajdkbinjava.exe -javaagent:S:javaideaIU-2020.3.2.winlibidea_rt.jar=56092:S:javaideaIU-2020.3.2.winbin -Dfile.encoding=UTF-8 -classpath C:Users279186856Desktop寒假java学习GUI_StudyoutproductionGUI_Study com.hu.net.TcpServer 你好,李焕英
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)