socket 出现 Connection refused问题

baidu_35142387 2016-05-27 09:51:03
(1)
import java.io.*;
import java.net.*;

import javax.sound.sampled.AudioFormat.Encoding;

public class Server {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

ServerSocket serverSocket = null;
PrintWriter out = null;
BufferedReader in = null ;

try{

serverSocket = new ServerSocket(8001);
}
catch (IOException e){
System.err .println("不能监听端口:8001.");

System.exit(1);
}
Socket incoming = null;
while(true)
{

incoming = serverSocket.accept();
out = new PrintWriter (incoming .getOutputStream (),
true);
in =new BufferedReader(new InputStreamReader(incoming
.getInputStream()));

out.println("发送消息给对方:");

out.println("输入Exit 退出。");

out.flush();

while(true){

BufferedReader br = new BufferedReader(new InputStreamReader
(incoming.getInputStream()));
String mess = br.readLine();
if(mess!=null){
String str = in.readLine();

if(str == null){

break;
}
else{
out .println(" "+str);
out .flush();
if(str .trim().equalsIgnoreCase("Exit")){

break;
}
}

}
else
System.out.println("请等待对方回复!");


out .close();
in.close();
incoming .close();
serverSocket .close();

}

}

}
}
(2) import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;


public class User {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null ;
try{

echoSocket = new Socket ("192.168.1.108" , 8001);

out = new PrintWriter(echoSocket .getOutputStream(),true);

in = new BufferedReader (new InputStreamReader (echoSocket.
getInputStream()));
}

catch (UnknownHostException e){
System .err .println("找不到服务器:localhost !");
System .exit(1);

}
String answer=in.readLine();

System .out.println(in.readLine());

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System .in));
String userInput;

while ((userInput = stdIn.readLine())!= null){

out.println(userInput);

System.out .println(in.readLine());
}

out .close();
in.close();
echoSocket .close();

}

}
这是两部分代码,请问哪里出错了?谢谢。
...全文
1866 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
yangminxing 2016-05-28
  • 打赏
  • 举报
回复
关防火墙。 或者用netstat查是否8001端口已经被占用

50,523

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧