java-TCP初步示例.

import java.io.*;
import java.net.*;
class TCPDemo
{
<wbr><br> }</wbr>

class Server
{
<wbr>public static void main(String[] args) throws Exception<br><wbr>{<br><wbr><wbr>ServerSocket ss = new ServerSocket(9527);<br><wbr><wbr>Socket s = ss.accept();<br><wbr><wbr><br><wbr><wbr>String ip = s.getInetAddress().getHostAddress();<br><wbr><wbr>//String name = s.getInetAddress().getHostName();<wbr> //解析过程较-慢</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>

<wbr><wbr>InputStream in = s.getInputStream();</wbr></wbr>

<wbr><wbr>byte [] b = new byte[1024];<br><wbr><wbr>int len = in.read(b);<br><wbr><wbr><br><wbr><wbr>System.out.print(ip + ".." + new String(b, 0, len));<br><wbr><wbr><br><wbr><wbr>OutputStream out = s.getOutputStream();<br><wbr><wbr><br><wbr><wbr>out.write("收到请求".getBytes());</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>

<wbr><wbr>s.close();<br><wbr><wbr>ss.close();<br><wbr>}<br> }</wbr></wbr></wbr></wbr></wbr>

class Client
{
<wbr>public static void main(String[] args) throws Exception<br><wbr>{<br><wbr><wbr>Socket s = new Socket("192.168.1.101", 9527);<br><wbr><wbr><br><wbr><wbr>OutputStream out = s.getOutputStream();<br><wbr><wbr>out.write("Tcp demo -&gt; run".getBytes());<br><wbr><wbr><br><wbr><wbr>InputStream in = s.getInputStream();<br><wbr><wbr>byte [] buf = new byte[1024];<br><wbr><wbr>int len = in.read(buf);</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>

<wbr><wbr>System.out.println(new String(buf,0,len));</wbr></wbr>

<wbr><wbr>s.close();<br><wbr>}<br> }<br></wbr></wbr></wbr>

你可能感兴趣的:(java)