import java.net.*;
import java.io.*;
class TcpClient
{
public static void main(String[] args) throws Exception
{
//创建客户端的Socket服务,指定目的主机和端口
Socket s = new Socket("196.168.1.103",10004);
//为了发送数据,应该获取socket流中的输出流
OutputStream os = s.getOutputStream();
os.write("tcp 来了".getBytes());
System.out.print(s.getInetAddress()+"...connected");
s.close();
}
}
class TcpServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10004);
//通过accept方法获取链接过来的客户端对象
Socket s = ss.accept();
//获取客户端的IP地址
String ip = s.getInetAddress().getHostAddress();
System.out.print(ip+"...connected");
//获取客户端发送过来的数据就要使用客户端对象的读取流来读取数据。
InputStream is = s.getInputStream();
byte[] buf = new byte[1024];
int len = is.read(buf);
String data = new String(buf,0,len);
System.out.println(data);
}
}
这是我看毕老师的视频写的代码可是 出现了下面的异常请大神讲解一下
Exception in thread "main" java.net.ConnectException: Connection timed out: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:519) at java.net.Socket.connect(Socket.java:469) at java.net.Socket.<init>(Socket.java:366) at java.net.Socket.<init>(Socket.java:180) at TcpClient.main(TcpDemo.java:23)
|
|