Я выполняю задание, которое состоит в создании двух java-кодов, общающихся друг с другом через сокеты. Когда я начал создавать два основных кода (общайтесь один раз), он работал нормально, но когда я пытался заставить их продолжать общаться оба Jammed!
Пожалуйста, прости мне отсутствие опыта и помоги мне ..
Код моего сервера,
/*****************************************************************************************
*
*
*
***************************************************************************************/
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
public class COMP_3270_Server implements Runnable {
public static void main(String[] args) {
try {
ServerSocket myServer = new ServerSocket(3270);
JOptionPane.showMessageDialog(null, "A server built over " +
InetAddress.getLocalHost().getHostAddress() + " : " +
myServer.getLocalPort() + "\nWaiting for masseges...",
"succeed", JOptionPane.INFORMATION_MESSAGE);
Socket channel = myServer.accept();
BufferedReader incomes = new BufferedReader(
new InputStreamReader(channel.getInputStream()));
PrintStream outgoes = new PrintStream(channel.getOutputStream());
String mssg = null;
do {
mssg = JOptionPane.showInputDialog("New Message: " + incomes.readLine());
outgoes.print(mssg);
} while (mssg != null);
JOptionPane.showMessageDialog(null, "The server will be closed now",
"Finish", JOptionPane.INFORMATION_MESSAGE);
channel.close();
myServer.close();
} catch (IOException e) {
System.out.println("Ops!, some thing went wrong. Please contect provider");
}
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}
и мой код клиента,
/*************************************************************
*
*
*
* ***********************************************************/
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
public class COMP_3270_Client implements Runnable {
public static void main(String[] args) {
try {
Socket channel = new Socket("localhost", 3270);
BufferedReader incomes = new BufferedReader(
new InputStreamReader(channel.getInputStream()));
PrintStream outgoes = new PrintStream(channel.getOutputStream());
JOptionPane.showMessageDialog(null, "Connected to: " +
channel.getInetAddress().getHostAddress() + " : " +
channel.getPort(), "succeed", JOptionPane.INFORMATION_MESSAGE);
String mssg = "New client: " + channel.getLocalAddress().getHostName();
outgoes.print(mssg);
System.out.println("222");
do {
mssg = JOptionPane.showInputDialog("New Message: " + incomes.readLine());
outgoes.print(mssg);
} while (mssg != null);
JOptionPane.showMessageDialog(null, "The channel will be closed now",
"Finish", JOptionPane.INFORMATION_MESSAGE);
channel.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Ops!, some thing went wrong. Please contect provider");
}
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}
это помогло !!!! Я почти закончил в моем назначении.
Вы, кажется, хорошо с проблемами Socket! Итак, я хочу воспользоваться некоторыми преимуществами;)
Есть ли у вас какие-либо идеи, как определить, является ли сообщение, выбрасывающее буфер, пустым? Я пробовал несколько методов, но ничего не получалось!
если ты хочешь увидеть мои коды после твоего (может, кому-то это понадобится,
/*****************************************************************************************
*
***************************************************************************************/
import java.awt.HeadlessException;
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
public class COMP_3270_Server
{
public static void main(String[] args)
{
try
{
ServerSocket myServer = new ServerSocket(3270);
JOptionPane.showMessageDialog (null, "A server built over " +
InetAddress.getLocalHost().getHostAddress() + " : " +
myServer.getLocalPort() + "\nWaiting for a client...", "succeed", JOptionPane.INFORMATION_MESSAGE);
Socket channel = myServer.accept();
BufferedReader income = new BufferedReader(new InputStreamReader(channel.getInputStream()));
PrintStream outgoes = new PrintStream(channel.getOutputStream());
String resp = " ";
String mssg = " ";
do
{
if (income.ready())
{
if(mssg.intern() == null)
{
int response = JOptionPane.showConfirmDialog(null,
"Client left sever, keep server alive?", "Client left",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.NO_OPTION)
{
resp = null;
}
else if (response == JOptionPane.CLOSED_OPTION)
{
resp = null;
}
else if (response == JOptionPane.YES_OPTION)
{
}
}
else
{
resp = JOptionPane.showInputDialog("New client message: " + mssg);
outgoes.println(resp);
}
}
}while (resp != null && mssg != null);
JOptionPane.showMessageDialog (null, "The server will be closed now", "Finish", JOptionPane.INFORMATION_MESSAGE);
channel.close();
myServer.close();
}
catch (HeadlessException e)
{
JOptionPane.showMessageDialog (null, "A string not supported", "Error", JOptionPane.INFORMATION_MESSAGE);
}
catch (UnknownHostException e)
{
JOptionPane.showMessageDialog (null, "IP address not available", "Error", JOptionPane.INFORMATION_MESSAGE);
}
catch (IOException e)
{
JOptionPane.showMessageDialog (null, "Failed or interrupted I/O", "Error", JOptionPane.INFORMATION_MESSAGE);
}
}
}
и
/*************************************************************
*
*
*
* References : http://www.youtube.com/watch?v=aEDV0WlwXTs
* ***********************************************************/
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
public class COMP_3270_Client
{
public static void main (String [] args)
{
try
{
String ip = JOptionPane.showInputDialog("Enter the IP you want to connect to: ");
Socket channel = new Socket(ip, 3270);
BufferedReader income = new BufferedReader(new InputStreamReader(channel.getInputStream()));
PrintStream outgoes = new PrintStream(channel.getOutputStream());
String strt = JOptionPane.showInputDialog("Succeed! Connected. You can say something: ");
outgoes.println(strt);
String resp = " ";
String mssg = " ";
do
{
if (income.ready())
{
mssg = income.readLine();
if(mssg.intern() == null)
{
JOptionPane.showMessageDialog (null, "Server closed!", "Session end",
JOptionPane.INFORMATION_MESSAGE);
resp = null;
outgoes.println(resp);
}
else
{
resp = JOptionPane.showInputDialog("New server message: " + mssg);
outgoes.println(resp);
}
}
}while (resp != null && mssg != null);
JOptionPane.showMessageDialog (null, "The channel will be closed now", "Finish", JOptionPane.INFORMATION_MESSAGE);;
channel.close();
}
catch (UnknownHostException e)
{
JOptionPane.showMessageDialog (null, "Wrong IP address or server reject connection", "Error", JOptionPane.INFORMATION_MESSAGE);
}
catch (IOException e)
{
JOptionPane.showMessageDialog (null, "Failed or interrupted I/O", "Error", JOptionPane.INFORMATION_MESSAGE);
}
}
}