首页 > 代码库 > TCP简单程序
TCP简单程序
服务器段:
package com.dcz.socket; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class TcpServer { public static void main(String[] args) { String data = "http://www.mamicode.com/你好啊,socket 世界!"; // 端口 int port = 17001; ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(port); System.out.println("服务端已经准备就绪......"); boolean isAccept = true; while (isAccept) { Socket client = serverSocket.accept(); InetAddress inetAddress = client.getInetAddress(); System.out.println("客户端ip:" + inetAddress); OutputStream clientOutputStream = client.getOutputStream(); clientOutputStream.write(data.getBytes()); clientOutputStream.close(); } serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
客户端代码:
package com.dcz.socket; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.UnknownHostException; import org.apache.commons.io.output.ByteArrayOutputStream; public class TcpClient { public static void main(String[] args) { String address = "127.0.0.1"; int port = 17001; Socket client = null; try { client = new Socket(address, port); InputStream serverInputStream = client.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while((serverInputStream.read(buffer, 0, buffer.length)) != -1){ byteArrayOutputStream.write(buffer, 0, buffer.length); } byte[] data = http://www.mamicode.com/byteArrayOutputStream.toByteArray();"utf-8")); byteArrayOutputStream.close(); client.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
TCP简单程序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。