我的服务器程序
import java.net.*;
import java.io.*;
public class MultiServe implements Runnable
{
static ServerSocket ss;
static Socket s;
public void run()
{
String name=Thread.currentThread().getName();
for(;;)
{
try
{
System.out.println("thread:"+name+"ready to accept");
s=ss.accept();
System.out.println("thread:"+name+" accepted");
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println("Thread"+name+"contacted You");
String sz,str1;
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader bk=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
while((sz=br.readLine())!=null)
{
System.out.println(sz);
str1=bk.readLine();
ps.close();
br.close();
bk.close();
s.close();
}
}
}catch(Exception e){}
}
}
public static void main(String args[]) throws IOException
{
MultiServe ms=new MultiServe();
ss=new ServerSocket(8080);
Thread t=new Thread(ms,"one");
Thread t1=new Thread(ms,"two");
t.start();
t1.start();
}
}
我的客户端程序
import java.net.*;
import java.io.*;
public class MultiClient
{
public static void main(String args[])throws Exception
{
Socket s=new Socket("localhost",8080);
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
String str,str1;
DataOutputStream ds=new DataOutputStream(s.getOutputStream());
BufferedReader bk=new BufferedReader(new InputStreamReader(System.in));
while(!(str=bk.readLine()).equals("exit"))
{
ds.writeBytes(str+"\n");
str1=br.readLine();
System.out.println(str1);
}
ds.close();
bk.close();
br.close();
s.close();
}
}
套接字编程新手但我能够连接但无法通信。我不知道它是否已陷入僵局。两者都在连接,但他们没有收到任何消息。
答案 0 :(得分:0)
这是因为你的try catch块..在try块中必定有一些错误。你有两个线程在同一个套接字上等待。当有人连接时,两人都试图接受它。
答案 1 :(得分:0)
您的代码不正确。
writeBytes(String)
的 DataOutputStream
方法将字符串写为byte数组,其中服务器上readLine()
的{{1}}方法需要一行文字。在这里,您可以在客户端使用BufferedReader
。
如果要继续阅读此套接字,则无法在每次读取后关闭服务器上的流。
尝试以下代码以达到预期效果:
服务器强>
PrintStream
<强>客户端:强>
public class Server implements Runnable
{
static ServerSocket ss;
static Socket s;
public void run()
{
String name=Thread.currentThread().getName();
for(;;)
{
try
{
System.out.println("thread:"+name+"ready to accept");
s=ss.accept();
System.out.println("thread:"+name+" accepted");
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println("Thread"+name+"contacted You");
String sz,str1;
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader bk=new BufferedReader(new InputStreamReader(System.in));
while((sz=br.readLine())!=null)
{
System.out.print(sz+"\nYour Msg:");
str1=bk.readLine();
ps.println(str1);
}
ps.close();
br.close();
bk.close();
s.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String args[]) throws IOException
{
Server ms=new Server();
ss=new ServerSocket(8080);
Thread t=new Thread(ms,"one");
//Thread t1=new Thread(ms,"two");
t.start();
//t1.start();
}
}