站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题Socket问题

Socket问题

摘要: Socket问题


public static void main(String[] args) throws Exception
{
Socket socket1=new Socket(-#34;192.168.1.2-#34;,8484);
InputStream in=socket1.getInputStream();
OutputStream out=socket1.getOutputStream();
out.write(-#34;hello-#34;.getBytes());
int tmp;
while((tmp=in.read())!=-1)
{
System.out.print((char)tmp);
}
in.close();
out.close();
socket1.close();
}

报错:

java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)

我把IP换成-#34;127.0.0.1-#34;也是报同样的错,我确定8484端口是空闲的,这问这是什么回事?





还要创建ServerSocket


class SocketServer extends Thread
{
private static Socket s;

public SocketServer(Socket s)
{
this.s = s;
}

public void run()
{
try
{
OutputStream os = s.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
InputStream is = s.getInputStream();
bos.write(-#34;hello,welcome you!-#34;.getBytes());
bos.flush();
byte[] buf = new byte[100];
int len = is.read(buf);
System.out.println(new String(buf, 0, len));
bos.close();
is.close();
s.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}

public static void main(String[] args)
{
try
{
ServerSocket ss = new ServerSocket(8484);
while(true)
{
s = ss.accept();
new SocketServer(s).start();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

先启动SocketServer,在另外一个dos启动你的客户端socket


↑返回目录
前一篇: 求找回密码功能源码(产生随机密码发到用户邮箱)
后一篇: 关于Varargs 的问题