关于java中Socket无法连接服务器的问题
packagetext10;importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava...
package text10;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
String s=null;
Socket mySocket;
DataInputStream in=null;DataOutputStream out=null;
try{
mySocket=new Socket("192.168.1.107",1234);
in=new DataInputStream(mySocket.getInputStream());
out=new DataOutputStream(mySocket.getOutputStream());
out.writeUTF("hello");
while(true)
{
s=in.readUTF();
if(s==null) break;
else System.out.println(s);
}
mySocket.close();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
} 展开
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
String s=null;
Socket mySocket;
DataInputStream in=null;DataOutputStream out=null;
try{
mySocket=new Socket("192.168.1.107",1234);
in=new DataInputStream(mySocket.getInputStream());
out=new DataOutputStream(mySocket.getOutputStream());
out.writeUTF("hello");
while(true)
{
s=in.readUTF();
if(s==null) break;
else System.out.println(s);
}
mySocket.close();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
} 展开
展开全部
c/s模式 你不仅需要一个client 还需要一个server
你只写了一个client,没用对应的server 当然无法连接了!
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author zc
* @version 2011-8-1 下午04:35:19
*/
public class Server {
public static void main(String[] args) {
Server server = new Server();
server.await();
}
public void await(){
try {
ServerSocket ss = new ServerSocket(1234);
while (true) {
Socket s = ss.accept();
System.out.println("accepted a request");
System.out.println(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
给你写了个简单的server
你只写了一个client,没用对应的server 当然无法连接了!
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author zc
* @version 2011-8-1 下午04:35:19
*/
public class Server {
public static void main(String[] args) {
Server server = new Server();
server.await();
}
public void await(){
try {
ServerSocket ss = new ServerSocket(1234);
while (true) {
Socket s = ss.accept();
System.out.println("accepted a request");
System.out.println(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
给你写了个简单的server
追问
谢谢 为什么运行后s=in.readUTF();
这句话还报异常啊
追答
建议你好好看一下socket编程...因为你的概念都不清楚
client的out是写给server的不是写个自己的
while (true) {
Socket s = ss.accept();
DataInputStream is = new DataInputStream(s.getInputStream());
System.out.println(is.readUTF());
System.out.println("accepted a request");
System.out.println(s);
}
你把上面的代码改下就知道了..你在client应该是读取server outputstream输出的东西..
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询